Created
February 5, 2017 03:35
-
-
Save clohr/6ec44674b1d0c5f8b1bb880adf9ebdbe to your computer and use it in GitHub Desktop.
fmap in Swift 3 to handle nil values
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
| // 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 ?? "") |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by https://robots.thoughtbot.com/functional-swift-for-dealing-with-optional-values