Created
June 26, 2017 19:57
-
-
Save djtech42/5dab3a47301a9bb26843dfc6c0ed4321 to your computer and use it in GitHub Desktop.
Swift Safe Unwrap Operators
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
var value: String? = "test" | |
value <*> { print($0) } <> { print("value is nil") } // OUTPUT: test | |
value = nil | |
value <*> { print($0) } <> { print("value is nil") } // OUTPUT: value is nil |
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
precedencegroup UnwrapPrecedence { | |
associativity: left | |
higherThan: UnwrapNonexistencePrecedence | |
} | |
precedencegroup UnwrapNonexistencePrecedence { | |
associativity: left | |
higherThan: BitwiseShiftPrecedence | |
} | |
infix operator <*> : UnwrapPrecedence | |
func <*><T>(value: T?, codeUsing: (T) -> Void) -> T? { | |
switch value { | |
case .some(let wrapped): codeUsing(wrapped) | |
case .none: break | |
} | |
return value | |
} | |
infix operator <> : UnwrapNonexistencePrecedence | |
func <><T>(value: T?, code: () -> Void) { | |
switch value { | |
case .some: break | |
case .none: code() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment