问题描述
根据《 Swift编程指南》,运算符重载是允许的,并且实际上相当通用.但是,我无法在操场上使用它.
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.
例如,Equatable
协议需要这样:func ==(lhs:Self, rhs:Self) -> Bool
For example, the Equatable
protocol wants this: func ==(lhs:Self, rhs:Self) -> Bool
假设我创建了一个简单的Location3D
结构:
Let's say I make a simple Location3D
struct:
struct Location3D
{
var x : Double
var y : Double
var z : Double
}
现在,我希望此Location3D
实现Equatable
协议,因此我将其与以下方法一起添加:
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
}
我得到仅在全局范围内允许操作符的编译器错误.嗯?
因此,我尝试将@infix
添加到函数中,将函数移至扩展名,将类型更改为类...全部无济于事.
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.
我错过了什么吗?当操作员似乎不起作用时,应该如何实现Equtable
和Comparable
?
Am I missing something? How are you supposed to implement Equtable
and Comparable
when operators don't seem to work?
推荐答案
您需要在全局范围内覆盖==运算符,但要使用参数类型.
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
这篇关于尚不支持运算符重载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!