Jacob Jacob - 6 months ago 23
Swift Question

Shouldn't UISwitch work the opposite way?

I'm confused over why my code works in the opposite way than I originally thought it would. Below is how my code currently functions:

//MARK: Actions
@IBAction func SwitchTap(sender: UISwitch) {
if mySwitch.on { //prints on if turning on
mySwitch.setOn(true, animated: true)
print ("switch is on")
}
else {
mySwitch.setOn(false, animated: true)
print("switch is off") //prints off if turning off
}


This is how I think it should work:

//MARK: Actions
@IBAction func SwitchTap(sender: UISwitch) {
if mySwitch.on {
mySwitch.setOn(**false**, animated: true) // should be false instead of true like in the previous example
print ("switch is on")
}
else {
mySwitch.setOn(**true**, animated: true) //should be true instead of false like in the previous example
print("switch is off")
}




I don't understand why the first version works but the second one doesn't. SetOn should turn the switch off when passed false as the first argument. Instead it is turning it off when passed true and simply doesn't change states.

Answer

Recall that UISwitch toggles its value on end-user's tap.

Your SwitchTap gets invoked together with the switch togging its value internally. Your first code leaves the state the same, so when the switch toggles it, the end result is a toggle. Your second code, however, inverts the state, so when `UISwitch' toggles it, the switch stays in its original state, because two toggles cancel each other.

Removing all calls to setOn will fix your code.