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?
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.
Explanation: . (dot) operator cannot be overloaded therefore the program gives error.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With