Initialize swift/swiftui var with 3 conditions [closed] - swift

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
I am trying to initialize a var with a couple of conditions
struct BreadCrumbCard: View {
var selection:String
var isSelected: Bool
var color = Color("Gray")
if(isSelected){ //error is here
color = Color("Yellow")
}else if(!selection.isEmpty){
color = Color("Green")
}else{
color = Color("Gray")
}
var body: some View{
...
"Expected declaration"
I've been searching for some time now but I can't find a way to do this or an alternative, I'm sure this must be obvious but I am new to swift. How can I initialize this variable with these conditions?

You can't put control code in a struct's or class's top-level scope, it must always be placed inside a function or similar context.
There's several ways to solve this problem, one way would be to use a computed property:
struct BreadCrumbCard: View {
var selection: String
var isSelected: Bool
var color: Color {
if isSelected { //error is here
return Color("Yellow")
} else if !selection.isEmpty {
return Color("Green")
} else {
return Color("Gray")
}
}
var body: some View{
Text("foo").foregroundColor(self.color)
}
}

Related

How can i import view which bring a closure with itself in SwiftUI? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
Here is my code, it does not work:
struct ContainerView<MyContent: View>: View {
let myContent: () -> MyContent
#State private var myValue: String = ""
var body: some View {
myContent() { value in
myValue = value
}
}
}
I want make this logic works, when I am bringing my view as myContent to body, I want be able to bring a string value with it like in code! I am not looking for reaching my goal with other ways, the goal of this question is be able to access value like in code as clouser.
Warning: I'm not sure what the use-case of this is -- it's not clear what problem is trying to be solved here, but there's likely a better fit that trying to make something like this work. This answer, though, does solve the compilation errors presented above.
Your syntax inside body implies that you want a trailing closure on myContent, but it's not defined in the signature. This would solve the compilation error:
struct ContainerView<MyContent: View>: View {
let myContent: (#escaping (String) -> Void) -> MyContent
#State private var myValue: String = ""
var body: some View {
Text(myValue)
myContent() { value in
myValue = value
}
}
}
Call site:
ContainerView { closure in
Button("Test") {
closure("Value")
}
}

How to access the variable out of scope of `if let` in swift [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
I am new to swift that I would like to use the variable funcReturn out of if let scope. anyway better way for me to do it other than using var to declare the variable?
if let funcReturn = localFunction() {
print(funcReturn)
}
print(funcReturn == "local function return value")
// i think I can do something like this but I do not need to change the value of funcReturn
if var funcReturn = localFunction() {
print(funcReturn)
}
print(funcReturn == "local function return value")
if let and if var only define the new variable inside the braces that follow. That is the way the language works.
Consider this code:
func foo() {
let aVar: Int? = 3
if let bar = aVar {
// bar is defined
}
// bar is not defined.
}
The same is true with an if var:
func foo() {
let aVar: Int? = 3
if var bar = aVar {
// bar is defined
}
// bar is not defined.
}
(The compiler will tell you that your var was never mutated.) But at the "// bar is not defined." comment, the variable bar still won't exist.
As the other poster says, guard works the opposite way:
func foo() {
let aVar: Int? = 3
guard let bar = aVar else {
return
}
// bar is defined for the rest of the function.
}
guard requires that you leave the current scope if it fails. (Usually with a return, although you can also do other things like break or continue from an outer loop.
The variable will only be in scope for the function. Another way to do it is a guard statement

Random Image when pressing a button in SwiftUI [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to make a random image appear on the screen, when I am pressing a button. I have three images which I want to be randomly shown, when I press the button. How do I do this?
If you are using an Array you can use the .randomElement(). Here's a simple example using the symbols from SF Symbols.
struct RandomImage: View {
#State var random: String = ""
var body: some View {
VStack {
Image(systemName: random)
Button(action: {
self.random = chooseRandomImage()
}) {
Text("Another one!")
}
}
}
}
var images = ["sun.max.fill", "moon.fill", "star.fill"]
func chooseRandomImage() -> String {
let array = images
let result = array.randomElement()!
return result
}

Swift - Merging 2 arrays of objects with a key [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm new to Swift programming and been working on an app fir a couple of weeks now, and I'm stuck at a crucial moment in the development.
I'm fetching data from a URL that returns a JSON. It is decoded and the data o is stored in an array.
I do the same thing with another URL.
Now I'm trying to initialize my final object wich will be a combination of 2 objects contained in each of the arrays.
Each array is a dictionary and each objects has a property call id.
I can't figure how I can go through each arrays to check for the id of each objects to match and then initialize a new object by combining the data from each object (look at the code below, it will make more sense hopefully)
I tried a for ... in but I couldn't access the id property and compare it. I tried to do a for ... in inside a for ... in to compare the id value: no success too.
On top of this, the initialization is also a challenge. I tried to implement something like this:
self.mergedList = (//result of the loops).map(MergedViewModel.init)
Here an example of the 2 objects
class MergeInformationViewModel {
var id = "1234"
var information = "This Is My Name"
}
class MergeDataViewModel {
var id = "1234"
var data = "Some very important data"
}
The object I'm trying to initialize
class MergedViewModel {
let mergedViewData: MergeDataViewModel
let mergedViewInformation: MergeInformationViewModel
init(data: MergeDataViewModel, information: MergeInformationViewModel) {
self.mergedViewData = data
self.mergedViewInformation = information
}
var id: String {
return self.mergedViewData.id
}
var information: String {
return self.mergedViewInformation.information
}
var data: String {
return self.mergedViewData.data
}
}
Finally the class handling the initialization. I'm working on a SwiftUI project
class MergedListViewModel: ObservableObject {
init() { mergingAndInit() }
#Published var mergedList = [MergedViewModel]()
var mergeInformationList = [MergeInformationViewModel]()
var mergeDataList = [MergeDataViewModel]()
func mergingAndInit() {
//...
}
}
the final result would look something like this
class MergedViewModel {
var id = "1234"
var information = "This Is My Name"
var data = "Some very important data"
}
How can I implement the func mergingAndInit() into my code?
Thanks in advance.
I figure it out!
for mergedI in mergeInformationList {
for mergedD in mergeDataList {
if mergedI.id == mergedD.id {
self.mergedList.append(MergedViewModel(data: mergedD, information: mergedI))
}
}
}

Set lazy var from outside without initializing [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I defined a class using a lazy var definition, where EXIFData is a struct:
struct EXIFData {
var a : String
var b : String
}
class xxx {
...
lazy var exif: EXIFData = {
...
return EXIFData(url: self.initUrl as CFURL)
}()
Now I want to assign a value to some members without executing the initial code of lazy var definition. How can I avoid it and assing an own created struct member instead like c.exif.a = newExif.a ? I'm using Swift 3.0.
Added:
I solved it this way: As part from the same class I use the needed information to assign my value within the lazy initialization. So there is only one additional "if" statement within. No need for external excess and special tricks to avoid standard initialization.
The lazy initializer won't run if you just assign a value normally before ever reading. Here's a test case:
class Class {
lazy var lazyVar: String = {
print("Lazy initializer ran")
return "Default value"
}()
}
let object = Class()
object.lazyVar = "Custom value"
print(object.lazyVar)