Created
June 20, 2016 18:57
-
-
Save guangLess/62004012edbfb53125ca739ccfaed969 to your computer and use it in GitHub Desktop.
different ways to unwrap optional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For option 2, No forced un-wrap needed in the map function (value is passed in unwrapped already)
Or, possibly better, avoiding all forced unwrapping by putting the setter right in the map
Of course then the compiler will force you to acknowledge that the map result is garbage (with
_ =
). So the ultimate solution might forcell.iconLabel.image
itself to beOptional
, such that this beauty would work:That is the most functionally idiomatic way to write it.
Option 3 is nice :)