Skip to content

Instantly share code, notes, and snippets.

@jnewc
Last active June 28, 2017 19:47
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 jnewc/131e6ee21a9e25c30664013c7e1f042f to your computer and use it in GitHub Desktop.
Save jnewc/131e6ee21a9e25c30664013c7e1f042f to your computer and use it in GitHub Desktop.
Conditional Execution Operators
/// Conditional execution operators
///
/// For a given argument:
/// * if the argument is truthy (i.e. true or non-nil), execute closure
/// * if the argument is falsy (i.e. false or nil), do not execute the closure
infix operator => : NilCoalescingPrecedence
public func =>(state: Bool, closure: @autoclosure () -> ()) {
if state { closure() }
}
public func =><T>(state: Bool, closure: @autoclosure () -> (T)) -> T? {
if state { return closure() }
return nil
}
public func =><T>(state: Optional<T>, closure: @autoclosure () -> ()) {
if state != nil { closure() }
}
public func =><T, U>(state: Optional<T>, closure: @autoclosure () -> (U)) -> U? {
if state != nil { return closure() }
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment