Skip to content

Instantly share code, notes, and snippets.

@Grantismo
Last active August 29, 2015 14:02
Show Gist options
  • Save Grantismo/3e1ba0412e911dfd7cfe to your computer and use it in GitHub Desktop.
Save Grantismo/3e1ba0412e911dfd7cfe to your computer and use it in GitHub Desktop.
Optional chaining for arbitrary operations
extension Optional{
func omap<K:Any>(optionalBlock:(T)->(K?))->K?{
if self{
return optionalBlock(self!)
}
return nil
}
}
@Grantismo
Copy link
Author

Swift introduces optional chaining which allows for succinct error handling:

if let roomCount = john.residence?.numberOfRooms {
    println("John's residence has \(roomCount) room(s).")
} else {
    println("Unable to retrieve the number of rooms.")
}

It's difficult however to chain other operators with optionals succinctly

if let residence = john.residence {
    if residence.numberOfRooms % 2 == 0  {
        println("John has an even number of rooms")
    }else{
    println("John has an odd number of rooms")
    }
} else {
    println("John has an odd number of rooms")
}

omap (optional map) allows succinct optional chaining with other operators. If the optional has a value, the value is passed to the user supplied closure. Otherwise a nil optional is returned.

if (john.residence.omap{r in r.numberOfRooms % 2 == 0}){
    println("John has an even number of rooms")
} else {
    println("John has an odd number of rooms")
}

or

if (john.residence.omap{$0.numberOfRooms % 2 == 0}){
     println("John has an even number of rooms")
} else {
     println("John has an odd number of rooms")
}

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