mercredi 16 janvier 2019

In swift for iOs,I have an if / else block of code, reacting to changes in a UISwitch. How to set the uiswitch back to off in some situations?

In my swift iOS application, I have a simple UISwitch control. I have connected the value changed outlet to my @IBAction. The code looks like this:

@IBAction func userDidSelectVisibiltySwitch(_ sender: Any) {

    if self.visibilitySwitch.isOn {
       if badCondition {
           self.visibilitySwith.setOn(false, animated: false)

          return
       }
     } else { // Strangely, it executes the else (I think because the compiler is evaluating the isOn condition again when it arrives to the else {}
        // work to be done if the user has turned off the switch
     }
}

I suspect that in this case, as I am turning the switch off before the else is evaluated, the compiler executes the else {} statement because it evaluates the above isOn expression again. But how is that possible, given that I placed a 'return' instruction ? that is really beyond me. A confirmation of my suspect comes from the fact that if I dispatch_async using GCD the 'self.visibilitySwith.setOn(false, animated: false)' statement, it works properly without executing the else {} statement, because the evaluation of the else takes place before the control is turned off by my statement. My code now looks like this, and it works:

@IBAction func userDidSelectVisibiltySwitch(_ sender: Any) {

    if self.visibilitySwitch.isOn {
       if badCondition {
            DispatchQueue.main.async {
               self.visibilitySwith.setOn(false, animated: false)
            }
            return
       }
     } else { // In this case it is normal, it does not execute the else {}
        // work to be done if the user has turned off the switch
     }
}

I think that I am missing something important of swift in this case. Any help is greatly appreciated. I have already provided a solution, but I want to understand the problem. Thanks a lot

Aucun commentaire:

Enregistrer un commentaire