Skip to content

Instantly share code, notes, and snippets.

@vlastachu
Created October 20, 2016 09:25
Show Gist options
  • Save vlastachu/4b722ce995f29cbad15c1b48fe4b0899 to your computer and use it in GitHub Desktop.
Save vlastachu/4b722ce995f29cbad15c1b48fe4b0899 to your computer and use it in GitHub Desktop.
infix operator .? : NilCoalescingPrecedence
func .?<ARG, RES> (fn: (ARG) -> RES, arg: ARG?) -> RES? {
if let arg = arg {
return fn(arg)
}
return nil
}
func .?<ARG0, ARG1, RES> (fn: (ARG0, ARG1) -> RES, arg: (ARG0?, ARG1?)) -> RES? {
if let arg0 = arg.0, let arg1 = arg.1 {
return fn(arg0, arg1)
}
return nil
}
// etc
let add: (Int,Int) -> Int = {$0 + $1}
let inc = {$0 + 1}
add .? (1, 2) // 3
add .? (nil, 2) // nil
// check precedence
inc .? nil ?? 1 + 1 // 3
(inc .? nil ?? 1 + 1) ?? 0 > 2 // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment