Search code examples
swiftxcodeuiswitch

Loading isOn or isOff for a UISwitch using Swift 4?


I am working on a project where I need to load a switch to either be .isOn or .isOff using Swift 4. I can do this in the main storyboard of the project by setting the switch to on or off, but I want the switch to be on or off based a boolean in my database for each user.

    //Create outlet for UISwitch
    @IBOutlet weak var switchBool1Outlet: UISwitch!

viewDidLoad() {
    //pulling data from Google Firebase to get true or false value    
    dataRef.reference().child("USERS/\(uid!)").observe(.value, with: { snapshot in
                    if let dictionary = snapshot.value as? [String: Any]
                    {
                        //MARK - Local Variables
                        var bool1Value = dictionary["bool1"] as! Bool

                        //trying to set switches here, this is not working
                        if bool1Value == true && bool1Value != nil {
                          //following throws error: "Expression resolves to an unused l-value"
                          self.switchBool1Outlet.isOn
                        }
        })
}

Any thoughts on how I can get my UISwitch to load on/off based on the true/false value in my database?


Solution

  • Use following code to change switch state, see here

    self.switchBool1Outlet.setOn(true, 
      animated: true)