Search code examples
operator-overloadingswift

Operator overloading not yet supported?


According to the Swift Programming Guide, operator overloading is allowed and actually quite versatile. However, I have been unable to get it working in the playground.

For example, the Equatable protocol wants this: func ==(lhs:Self, rhs:Self) -> Bool

Let's say I make a simple Location3D struct:

struct Location3D
{
    var x : Double
    var y : Double
    var z : Double
}

Now I want this Location3D to implement the Equatable protocol, so I add it along with this method:

func ==(lhs: Self, rhs: Self) -> Bool
{
    return lhs.x == rhs.x &&
           lhs.y == rhs.y &&
           lhs.z == rhs.z
}

I get the compiler error of operators are only allowed at global scope. Huh?

So I tried adding @infix to the function, moving the function to an extension, changing the type to a class instead... all to no avail.

Am I missing something? How are you supposed to implement Equtable and Comparable when operators don't seem to work?


Solution

  • You need to override the == operator in the global scope but with your type for the arguments.

    In this case it means you declare your struct to conform to the protocol and then simply implement the function outside it's scope.

    struct Location3D : Equatable {
        // ...
    }
    
    func ==(lhs: Location3D, rhs: Location3D) -> Bool {
        // ...
    }
    

    See the library reference for further discussion:

    https://developer.apple.com/documentation/swift/equatable