Honey Honey - 2 years ago 72
Swift Question

How does optional binding function different from optional chaining?


I am learning from a tutorial from Raywenderlich. My question is why do we use an optional binding ie

if let
what difference does it make? Why can't we use optional chaining—similar to Line A & B ?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("IconCell", forIndexPath: indexPath)
let icon = icons[indexPath.row]

cell.textLabel?.text = icon.title // Line A
cell.detailTextLabel?.text = icon.subtitle // Line B

if let imageView = cell.imageView, iconImage = icon.image { //Line C
imageView.image = iconImage

The instructor's explanation is :

When we instance an icon we get a reference to the image based on a string...if for whatever reason that image isn't included in the bundle, renamed or deleted, then that icon may not have an image associated with it...and we have to use if let to make sure it is there.

I still don't understand the difference.

Answer Source

If you are thinking of

cell.imageView?.image = icon.image  // let's call this Line D

this is not equivalent to Line C.

If cell.imageView is not-nil, while icon.image is nil, line D will erase the original image of the imageView by setting it to nil.

However, in line C the condition will not be entered, thus keeping the original image even if icon.image is nil.

Line C is equivalent to

if let image = icon.image {
    cell.imageView?.image = image

I guess your professor just like to make it more explicit.

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