Skip to content

Instantly share code, notes, and snippets.

@clohr
Created February 5, 2017 03:35
Show Gist options
  • Select an option

  • Save clohr/6ec44674b1d0c5f8b1bb880adf9ebdbe to your computer and use it in GitHub Desktop.

Select an option

Save clohr/6ec44674b1d0c5f8b1bb880adf9ebdbe to your computer and use it in GitHub Desktop.
fmap in Swift 3 to handle nil values
// fmap
precedencegroup ComparisonPrecedence {
associativity: left
}
infix operator <^> : ComparisonPrecedence
func <^><A, B>(f: (A) -> B, a: A?) -> B? {
switch a {
case .some(let x):
return f(x)
case .none:
return .none
}
}
// example
var nameString: String? = "Bob" // could also be nil
//nameString = nil
func usernameFormat(name: String) -> String {
return "@\(name)"
}
let handle = usernameFormat <^> nameString
print(handle ?? "")
@clohr
Copy link
Copy Markdown
Author

clohr commented Feb 5, 2017

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