0

I wanted to be able to add two (Int,Int) tuples. So I defined

func + (left:(Int,Int), right:(Int,Int)) -> (Int,Int) {
    return (left.0 + right.0, left.1 + right.1)
}

but Xcode is not happy, saying:

consecutive declarations on a line must be separated by ';'

What's wrong with my infix operation?

pkamb
  • 33,281
  • 23
  • 160
  • 191
user1258240
  • 855
  • 7
  • 15

2 Answers2

0

Ok, I leave this question on since others may find it useful, but I found the answer. Turns out operators can only be defined in global scope - at least that's what xcode just told me. So I moved the definition of + out of the class it was in, and now it all works. I'm still not sure what you do if you want to define an operator over a struct, say, that is only defined within a class, but hey, I just needed it for Int tuples...

user1258240
  • 855
  • 7
  • 15
  • So your problem is unrelated to tuples ... perhaps update the title and the question to make that clear for future readers. And actually your question now seems to be a duplicate of http://stackoverflow.com/questions/24467960/swift-equatable-protocol or http://stackoverflow.com/questions/24148135/operator-overloading-not-yet-supported – Martin R Mar 28 '15 at 17:10
  • Thanks Martin. But regarding it being a duplicate, while the answer is the same, I think the question is not. I asked it after I tried unsuccessfully to find the answer: the links you give are specifically about the equatable protocol and my answer is about operators. But i'll remove the tuple label... – user1258240 Mar 28 '15 at 17:35
-1

If you want to define an infix operator at the class/struct level, you have to mark it as static. For example:

struct Foo {
    var prop: Int

    static func + (lhs: Foo, rhs: Foo) -> Foo {
        return Foo(prop: lhs.prop + rhs.prop)
    }
}
John Montgomery
  • 6,739
  • 9
  • 52
  • 68