Why set delegate = delegate on Checklist app pg 221

Hi,

For the Checklist app - on pg 221 - why do we have to set delegate = delegate? What does that accomplish?

override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
if let delegate = delegate {
let iconName = icons[indexPath.row]
delegate.iconPicker(self, didPick: iconName)
}
}

Thanks!

The delegate property is an optional, so it can be nil.

You can’t write delegate.iconPicker(...) if delegate is nil because that will crash the app.

So first we “unwrap” the optional into a regular variable. That is what this line does: if let delegate = delegate {. It takes the delegate property, which is an optional, and if it is not nil, unwraps it into a new variable, also called delegate.

This new delegate is guaranteed to be non-nil, and therefore we can finally call delegate.iconPicker(...).

This is a pattern you’ll see a lot in Swift code. It’s explained several times in more detail in the book, so don’t worry too much if it doesn’t make much sense yet. :wink: