Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 777
Erik Avatar asked Jun 10 '14 18:06

Erik


People also ask

Why is operator overloading not supported in Java?

Java doesn't supports operator overloading because it's just a choice made by its creators who wanted to keep the language more simple. Every operator has a good meaning with its arithmetic operation it performs. Operator overloading allows you to do something extra than what for it is expected for.

Which operator Cannot be used in operator overloading?

Explanation: . (dot) operator cannot be overloaded therefore the program gives error.

Is operator overloading supported in C++?

C++ allows us to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading, respectively.

What are the restrictions of operator overloading?

1) Only built-in operators can be overloaded. New operators can not be created. 2) Arity of the operators cannot be changed. 3) Precedence and associativity of the operators cannot be changed.


1 Answers

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

like image 197
hallski Avatar answered Oct 12 '22 17:10

hallski