Is there any simple examples of the ability to grab a variable from a function? For instance, if a certain thing happens in a function, then += 1
would be added to the variable. I'd like to grab that variable and use it in a Conditional statement in the View. Example below which I'm not sure how to work.
I have a function like so below:
func mspEL() -> Int {
var msp = 0
if age > 18 {
print("Elig")
msp += 1
} else {
print("No"
}
I have a View called ResultsView() which I'm trying to grab the msp variable from the function above and use it in a Conditional statement to show some Text. Eg; If the variable is greater than 0, write this Text.
struct ResultsView: View {
@State var result = msp
var body: some View {
if result > 0 {
Text("You are Eligible!")
} else {
print("")
}
}
}
There is certainly a better way to do it, but this works:
struct ContentView: View {
@State var result = 0
@State var elig = true
@State var age = 19 // That value will have to be set somewhere
func mspEL(age: Int) -> (Int, Bool) {
if age > 18 {
print("Elig", "msp=", result+1)
return (result + 1, true)
} else {
print("No", "msp=", result)
return (result, false)
}
}
var body: some View {
Button(action: {
let someAge = (0..<30).randomElement()
(result, elig) = mspEL(age: someAge ?? 0)
age = someAge ?? 0
}) {
Text("Button")
}
if elig {
Text("Eligible with age \(age)")
} else {
Text("Nonligible with age \(age)")
}
}
}