Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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