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
@autoclosure
annotation, and therhs
for both has to returnVoid
instead ofAny
.This way if I do:
the
@autoclosure
one will get called, regardless of whetherdoSomething()
returns anything or not.And if I do:
the one without the
@autoclosure
will be called because the closure is of type()->Void
.