Skip to content

Instantly share code, notes, and snippets.

@guangLess
Created June 20, 2016 18:57
Show Gist options
  • Save guangLess/62004012edbfb53125ca739ccfaed969 to your computer and use it in GitHub Desktop.
Save guangLess/62004012edbfb53125ca739ccfaed969 to your computer and use it in GitHub Desktop.
different ways to unwrap optional
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! LineTableViewCell
let eachLine = subwayDataStore.subwayArrayList[indexPath.row]
Optional option 1 :
if let iconName = eachLine.letter {
cell.iconLabel.image = UIImage(named:iconName.lowercaseString)
}
Optional option 2 :
let imageName = eachLine.letter.map {_ in
eachLine.letter!.lowercaseString
}
cell.iconLabel.image = UIImage(named:imageName!)
Optional option 3:
let image = eachLine.letter.map {
UIImage(named: $0)
}
cell.iconLabel.image = image!
cell.nameLabel.text = eachLine.name
cell.descLabel.text = eachLine.desc
return cell
}
@adamkaplan
Copy link

adamkaplan commented Jun 20, 2016

For option 2, No forced un-wrap needed in the map function (value is passed in unwrapped already)

    let imageName = eachLine.letter.map { (letter: String) in 
        return letter.lowercaseString
    }
    cell.iconLabel.image = UIImage(named:imageName!)

Or, possibly better, avoiding all forced unwrapping by putting the setter right in the map

_ = eachLine.letter.map { (letter: String) in
    cell.iconLabel.image = UIImage(named: letter.lowercaseString)
}

Of course then the compiler will force you to acknowledge that the map result is garbage (with _ =). So the ultimate solution might for cell.iconLabel.image itself to be Optional, such that this beauty would work:

cell.iconLabel.image  = eachLine.letter.map { (letter: String) in
    return UIImage(named: letter.lowercaseString)
}

That is the most functionally idiomatic way to write it.

Option 3 is nice :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment