Skip to content

Instantly share code, notes, and snippets.

@nottombrown
Created August 14, 2014 22:52
Show Gist options
  • Save nottombrown/c6585cad9588a9dc5383 to your computer and use it in GitHub Desktop.
Save nottombrown/c6585cad9588a9dc5383 to your computer and use it in GitHub Desktop.
extension Optional {
func try<U>(f: (T) -> U) -> Optional<U> {
if let unwrapped = self {
return f(unwrapped)
} else {
return nil
}
}
}
func formatLegCount(legCount: Int) -> String {
return "It has \(legCount) legs"
}
let numberOfLegs = ["ant": 6, "snake": 0, "cheetah": 4]
let possibleLegCount = numberOfLegs["ant"]
let possibleString:Optional<String> = possibleLegCount.try(formatLegCount)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment