Search code examples
swifttuplescustom-operator

How can I define a postfix operator on a tuple?


I have the following code:

postfix operator ^^^
public postfix func ^^^(lhs: Int) -> Int {
    return 0
}

public postfix func ^^^<T>(lhs: (T, T)) -> [T] {
    return [lhs.0, lhs.1]
}

func go() {
    1^^^ // this works
    (0, 0)^^^ // error: Unary operator '^^^' cannot be applied to an operand of type '(Int, Int)'
}

For which I get the error, Unary operator '^^^' cannot be applied to an operand of type '(Int, Int)'. Any ideas how to fix this?


Solution

  • That is a known bug, compare Prefix and postfix operators not working for tuple types in the Swift forum and SR-294 Strange errors for unary prefix operator with tuple arg.

    It has been fixed for Swift 5, the following compiles and runs in Xcode 10.2 beta 4:

    postfix operator ^^^
    
    public postfix func ^^^<T>(lhs: (T, T)) -> [T] {
        return [lhs.0, lhs.1]
    }
    
    let x = (0, 0)^^^
    print(x) // [0, 0]