Search code examples
swifttuplesprefix-operator

Define a prefix operator on a Swift tuple


This is probably a swiftc bug, but defining a prefix operator on a tuple doesn't seem to work:

typealias Pt = (x: Int, y: Int)
prefix func - (p: Pt) -> Pt { return (-p.x, -p.y) }
-Pt(5,6)

Results in:

error: unary operator '-' cannot be applied to an operand of type '(Int, Int)'
-(5,6)
 ^

Is this my bug or Swift's? Or is there a workaround?

Note that defining Pt as a struct works fine:

struct Pt { var x: Int, y: Int }
prefix func - (p: Pt) -> Pt { return Pt(x: -p.x, y: -p.y) }
-Pt(x: 5, y: 6)  // is equal to Pt(x: -5, y: -6)

and that infix operators on tuples work fine too.


Solution

  • Never mind folks; I think this is just a bug.

    As I noted in my comment above, there's this bug filed for it (which you might vote for if you're having this problem).