Kevin
Kevin

Reputation: 1189

Swift Setting up a global variable

I am having trouble receiving a variable through different functions.

I've assigned:

 var ageDescription: String = String()

outside of the class as a global variable, as well as 2 ibactions

@IBAction func ageChanged(sender: UISegmentedControl) {
    switch age.selectedSegmentIndex {
    case 0:
        print("Under 18")

        let ageDescription = "under 18"
    case 1:
        print("Over 18")

        let ageDescription = "over 18"
    case 2:
        print("Strictly over 21")
        let ageDescription = "strictly over 21"
    default:
        print("IDK")
    }


}



@IBAction func saveButtonTapped(sender: UIButton) {
    print(ageDescription)
}

I want the user to be able to select a choice for ages, and the saveButton to print out the result. But it seems after the saveButton has been tapped, it prints out a nil. I believe it has something to do with the variable ageDescription, but I am not sure what is wrong.

Upvotes: 3

Views: 469

Answers (3)

M_G
M_G

Reputation: 1208

Besides using global variables is easily becoming a code smell you are instantiating a local variable in your switch statement. This will overlap the scope of the global variable at the time of assignment. That's why the global variable is never changed. Just remove the 'let' keyword to use the global variable instead.

Upvotes: 1

Santosh
Santosh

Reputation: 2914

You are assigning the value to new variable inside a function and trying to access the global variable in another function, hence it is nil for you. Since you have declared a global variable, no need to declare another local variable inside ageChanged function, just access the global var.

Try this:

@IBAction func ageChanged(sender: UISegmentedControl) {
    switch age.selectedSegmentIndex {
    case 0:
        print("Under 18")

        ageDescription = "under 18"
    case 1:
        print("Over 18")

        ageDescription = "over 18"
    case 2:
        print("Strictly over 21")
        ageDescription = "strictly over 21"
    default:
        print("IDK")
  }
}

Upvotes: 4

Pranav Wadhwa
Pranav Wadhwa

Reputation: 7736

Remove the let in the switch statement. You are recreating the ageDescription variable.

Upvotes: 2

Related Questions