Kevin Kevin - 3 months ago 21
Swift Question

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.

Answer

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