Swift check uiswitch status on viewDidLoad

3.3k views Asked by At

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?

3

There are 3 answers

1
Pradeep K On BEST ANSWER

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")   
}
0
Andrea On

You must call super. All IBOutlets are implicitly unwrapped optional. The are nil until awakeFronNib is called. If you try to access one of them before that you get an exception.
Also verify that the outlet to the switch is connected.

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

Check switch ON/OFF

if switchTapped.isOn == true {
        switchTapped.isOn = true
    }else {
        switchTapped.isOn = false
    }