Amazing technique to embed non-optional assignments within a comma separated “if let” statement

The problem is, you have this complex set of assignments to complete before you can take an action, and most of them are optionals – but not all:


for cell in tableView.visibleCells {
  if let indexPath = tableView.indexPathForCell(cell) {
    let user = users[indexPath.row]
    if let ratingLabel = cell.contentView.viewWithTag(100) as? UILabel { 
      setRatingLabel(ratingLabel, user: user)
    }
  }
}

Now imagine more assignments, a few optionals then a non-optional – it regresses to the old “cascading if let” situation in pre-Swift 1.2 code.

This type of situation appears in my code all the time, so I

posted a question on the Apple internal Swift forum asking for suggestions.

Fortunately, it was answered by OOper! It seems that you can embed a non-optional assignment by prefix it with “case”:


for cell in tableView.visibleCells {
if let indexPath = tableView.indexPathForCell(cell),
   case let user = users[indexPath.row],
   let ratingLabel = cell.contentView.viewWithTag(100) as? UILabel
   {
     setRatingLabel(ratingLabel, user: user)
   }
}

I’d love to say I completely understand why it works – I think it’s because ‘case’ statements can fail or succeed. In any case all my code using this works just fine.

While looking a bit odd, the final code is more compact and easier to follow.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s