Georges Sources Georges Sources - 1 month ago 8
Swift Question

Acces variable IBaction

Hi I need help my function doesn't access my boolean. My switch IBaction is suppose to change it but doesn't seem to update that variable in my second file.

@IBAction func saveClubSwitchPressed(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: "ClubState")
if(sender.isOn == true)
{
clubSwitchBool = true
print(stateClubSwitchBool())
}else
{
clubSwitchBool = false
print(stateClubSwitchBool())
}
}
func stateClubSwitchBool() -> Bool
{
return clubSwitchBool
}


This is my function that access my boolean in another file:

override func loadView() {
super.loadView()

var clubSwitchBool1 = getSwitchBool()

}

Answer Source

Where do you declare/initialize the clubSwitchBool variable?

You can simplify your function but having clubSwitchBool read the isOn attribute.

@IBAction func saveClubSwitchPressed(_ sender: UISwitch) {
    UserDefaults.standard.set(sender.isOn, forKey: "ClubState")
    clubSwitchBool = sender.isOn
    print(stateClubSwitchBool())
}

EDIT:

Have your clubSwitchBool1 read from UserDefaults:

clubSwitchBool1 = UserDefaults.standard.bool(forKey: "ClubState")