Using a variable from a Function

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("")
            }
        }
    }
Answered by Claude31 in 704999022

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)")
        }
    }
}

Can you be a bit more specific with what you are trying to do? You could potentially use an inout variable https://www.hackingwithswift.com/sixty/5/10/inout-parameters, and modify the variable if the condition occurs inside your function.

The code you posted is quite incomplete. We don't see where you are calling mspEL().

There is also an error, missing closing parenthesis in print:

func mspEL() -> Int {
  var msp = 0

  if age > 18 {
      print("Elig")
      msp += 1
  } else {
     print("No")   // <<--
  }

In addition, you don't pass age as a parameter to this func. Why ? Where is age defined ?

And finally, msp is declared locally, not visible outside the func. And each time, map is reset to zero !And your func has no return. It will not compile.

So, maybe func should be:

var msp = 0    // declare outside

func mspEL(age: Int)  {    // No value returned

  if age > 18 {
      print("Elig")
      msp += 1
  } else {
     print("No")   // <<--
  }
}

But you should restructure code as follows:

struct ContentView30: View {
    @State var result = 0
    var age = 19  // That value will have to be set somewhere
    
    func mspEL(age: Int) -> Int {
        
        if age > 18 {
            print("Elig", "msp=", result)
            return result + 1
        } else {
            print("No", "msp=", result)
            return result
        }
    }
    
    var body: some View {
        Button(action: {
            result = mspEL(age: age)
            
        }) {
            Text("Button")
        }
    }
}

and call in Preview or SceneDelegate as:

let contentView = ContentView30(result: 0)

@Claude31 Thank you for that. Initially I was looking for a basic example to put into my app but maybe it's me not being able to understand it fully. Let me show you my full code for better transparency.

At the Bottom and outside of my ApplicationView(), I have a function below which is passing through some parameters that Prints in the console.     

        var ssdi = 0

    func ssdiEligibility() {
        if disabled == true && income <= 803 {
            print("SSDI Eligible")
            ssdi += 1
        } else if ssdiBen == true || ssiBen == true {
            print("")
        } else {
            print("")
        }
    }

Now, Back to the ApplicationsView(), I have a button which once selected (below), will run that function and also hop to another view called ResultsView.

                ZStack {
                    VStack {
                        Button(action: {ssdiEligibility()
                            self.isOpen = true
                        }, label: {
                            Text("View Results")
                        }).sheet(isPresented: $isOpen, content: {
                            ResultsView()
                        })
                    }
                }

What I'd like to happen is once the View Results button is selected and the ResultsView() populates along with initiating the ssdiEligibility() function, I'd like to show "Eligible for SSDI" on the View itself as Text and not just printing in the console.

So, my concept was, if I create a variable var ssdi = 0 in the function and add '1' if the first condition in the function is true, and using the button View Results button to also calculate if ssdi > 0 then write as Text on the Results View that "They are Eligible for SSDI"

Any thoughts?

Accepted Answer

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)")
        }
    }
}
Using a variable from a Function
 
 
Q