Search code examples
swiftif-statementstructvar

Swift - Can you create conditional vars?


Is it possible to change a var's value conditionally?

I have a menu structure that needs to appear differently depending on whether some calculations have taken place, active = true/false.

Below is what I would LIKE to write but clearly you can't put a conditional within a var statement. How could I achieve this?

struct Results: Identifiable {
var id = UUID().uuidString
var category: String
var active: Bool
}

var results = [
    if GlobalVariables.calculated == true {
        Results(category: "Results", active: true)
    } else {
        Results(category: "Results", active: false)
    }
]

Solution

  • for this simple case, you could try using a ternary, like this:

    var results = [ GlobalVariables.calculated ? Results(category: "Results", active: true) : Results(category: "Results", active: false)
    ]
    
    print("---> results: \(results) \n")