Reputation: 369
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?
Upvotes: 1
Views: 3396
Reputation: 500
Check switch ON/OFF
if switchTapped.isOn == true {
switchTapped.isOn = true
}else {
switchTapped.isOn = false
}
Upvotes: 0
Reputation: 26385
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"
}
}
Upvotes: 2
Reputation: 3661
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")
}
Upvotes: 1