2

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?

meisel
  • 2,151
  • 2
  • 21
  • 38
  • Yes, I see what you mean! Looks like postfix operators don't work with tuples. Not very surprising really. Maybe you could use a struct instead in your real use case. Tuples are really a sort of substandard type and there are a lot of things they don't do (for example, tuple equality has always been a major issue as well). – matt Mar 22 '19 at 18:05
  • Never even thought about define operators on tuples. Though if I saw `(0, 0)^^^` in a codebase, heads would roll :p – Alexander Mar 22 '19 at 18:06
  • Tuples have some very nice uses as sequences, e.g.: `(x, y, width, height) = ("x", "y", "width", "height")^^^.map { dict[$0] }` would get a frame from a dictionary of `String` to `Int`. – meisel Mar 22 '19 at 18:06
  • @Alexander I just used `^^^` to make it *very* clear this was not an existing operator with conflicts :P – meisel Mar 22 '19 at 18:07
  • The big reason operators are nice for tuples is because you can't extend them, so adding methods is out of the question. *And* you can do infix operators on tuples. Just not postfix I guess? – meisel Mar 22 '19 at 18:08

1 Answers1

3

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]
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382