Swift Optionals Clarifiaction Required

Fittoburst

I hope someone can explain this to me.... (still quite new to Swift!)

This line fails if part is nil...

    cell?.myTextField.text = part?.number

(fatal error: unexpectedly found nil while unwrapping an Optional value)

whereas this line works...

    cell?.myTextField?.text = part?.number;

In both cases, if cell is not nil, myTextField will exist. I would have thought that if part is nil, the line fails and text will not be set. But I have to set myTextField to an optional to get this line to 'pass'.

Can someone explain why this is? My confusion lies at having to append the ? to the end of myTextField.

vacawama

I was able to recreate your issue, (mostly) with the following:

class Part {
    var number:String = "3"
}

class TextField {
    var text: String! = nil
}

class Cell {
    var myTextField: TextField! = nil
}

var part: Part? = nil
var cell:Cell? = Cell()

cell?.myTextField.text = part?.number    // crashes
cell?.myTextField?.text = part?.number   // works

It crashes because myTextField is an implicitly unwrapped optional, an since cell exists, but myTextField is nil, it crashes trying to unwrap the optional.

If you add a ? to myTextField, the entire expression becomes an optional chain that results in nil because myTextField is nil. In this case it doesn't crash because the optional chain doesn't try to unwrap myTextField.

The optional chain on the right hand of the assignment has no effect on whether the assignment happens or not. If the optional chain on the right hand side of = is nil, then nil will be assigned to the left hand side. Only the left hand side can cancel the assignment if it is an optional chain.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related