SLN SLN -5 years ago 153
iOS Question

Assign a nil to a forced unwrapping optional doesn't crash the code, why is that?

I'm on the initial way of building a calculator. Currently, the code is doing nothing but printing the digits and Pi into the calculator's label while user taps it.

1) Che Code

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var display: UILabel! = nil //Look Here "(

var userIsInTheMiddleOfTypeing = false

@IBAction func touchDigit(_ sender: UIButton){
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypeing {
let textCurrentlyInDisplay = display.text!
display.text = textCurrentlyInDisplay + digit
} else {
display.text = digit

userIsInTheMiddleOfTypeing = true

@IBAction func performOperation(_ sender: UIButton) {
userIsInTheMiddleOfTypeing = false
if let methematicalSymbol = sender.currentTitle {
if methematicalSymbol == "π" {
display.text = String(M_PI) // M_PI

2) UI

The touchDigit function is linked to all the digit buttons as shown in the following figure. The display is the
while performOperaton is the PI button

enter image description here

Question: You may found the line (Third line of the code)
UILabel! = nil
. I think adding a
to a forced unwrapping optional would crash the code, but it doesn't and so far, the code works fine. Why is that?

Answer Source

Unwrapped optional is a contract with the compiler that the value won't be nil when it is accessed. Consider the following playground code.

var x: Int! = nil // It's declared as an unwrapped optional *var*
x = 5 // So assigning to it is OK
var y: Int = x // you can access its value, if it's not nil
x = nil // even assigning nil is OK
//y = x // CRASH. *Accessing* it when nil causes an error

Adding = nil in your declaration is actually spurious - if you dropped it, the variable would still be initialised as nil, and, as @MartinR pointed out in comments, your outlet will be assigned to when the Xib is loaded.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download