iosswiftuiswitchviewdidloadunwrap

Swift check uiswitch status on viewDidLoad


I have a problem with uiswitch. I need to know if uiswitch is on or off when app run first time. i tried with this code:

@IBOutlet weak var switch1: UISwitch!

override func viewDidLoad() {
    super.viewDidLoad()
    if switch1.on {
        print("Switch is on")            
    } else {
        print("Switch is off")
    }
}

but everytime i get this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

How i can unwrap uiswitch without get that error?


Solution

  • May be your switch1 is not connected to the UISwitch in your storyboard or xib.

    if let switch = switch1 {
      if switch.on {
         print("switch is on")
      } else {
         print("switch is off")
      }
    } else {
       println("Where's the switch")   
    }