Skip to content

Instantly share code, notes, and snippets.

@djtech42
Created June 26, 2017 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djtech42/5dab3a47301a9bb26843dfc6c0ed4321 to your computer and use it in GitHub Desktop.
Save djtech42/5dab3a47301a9bb26843dfc6c0ed4321 to your computer and use it in GitHub Desktop.
Swift Safe Unwrap Operators
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
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