I have this custom operator:
infix operator ?> : NilCoalescingPrecedence
func ?> (lhs: Any?, rhs: @autoclosure ()->Any) {
if lhs == nil {
print("lhs is nil")
rhs()
}
}
Usage:
optional ?> {
print("executing")
}
The problem is, when the lhs is nil, the closure is not executing. In the console "lhs is nil" is printing, but no "executing" is printing afterwards. How is the "lhs is nil" print statement executed but not rhs?
The solution seems to be add an overload to the operator with exactly the same signature, except for that it doesn't have the
@autoclosureannotation, and therhsfor both has to returnVoidinstead ofAny.This way if I do:
the
@autoclosureone will get called, regardless of whetherdoSomething()returns anything or not.And if I do:
the one without the
@autoclosurewill be called because the closure is of type()->Void.