Search code examples
swiftclosurescustom-operator

Function being called but not executing


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?


Solution

  • 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 the rhs for both has to return Void instead of Any.

    infix operator ?> : NilCoalescingPrecedence
    func ?> (lhs: Any?, rhs: @autoclosure ()->Void) {
        if lhs == nil {
            print("lhs is nil")
            rhs()
        }
    }
    func ?> (lhs: Any?, rhs: ()->Void) {
        if lhs == nil {
            print("lhs is nil")
            rhs()
        }
    }
    

    This way if I do:

    optional ?> doSomething()
    

    the @autoclosure one will get called, regardless of whether doSomething() returns anything or not.

    And if I do:

    optional ?> {
        doSomething()
        doSomethingElse()
    }
    

    the one without the @autoclosure will be called because the closure is of type ()->Void.