我已经看到了这个 Swift Equatable Protocol 的答案提到如何在全局范围内声明 ==
方法的问题。
如果我不采用 Equatable
,我仍然可以声明 ==
来测试我的两个类型之间的相等性。
// extension Foo: Equatable {}
func ==(lhs: Foo, rhs: Foo) -> Bool {
return lhs.bar == rhs.bar
}
struct Foo {
let bar:Int
}
事实上,它的实现需要在全局范围内声明,这使得它看起来偶然并且区别于一个协议(protocol),即使Equatable
被采用。
Equatable
协议(protocol)不仅仅是语法糖,只是让(我们和)编译器安全地知道我们的类型实现了协议(protocol)所需的方法吗?
为什么必须全局声明运算符实现,即使是协议(protocol)?这是因为调度运算符(operator)的方式不同吗?
最佳答案
更新
来自 Xcode 8 beta 4 发行说明:
Operators can be defined within types or extensions thereof. For example:
struct Foo: Equatable { let value: Int static func ==(lhs: Foo, rhs: Foo) -> Bool { return lhs.value == rhs.value } }
Such operators must be declared as
static
(or, within a class,class final
), and have the same signature as their global counterparts. As part of this change, operator requirements declared in protocols must also be explicitly declaredstatic
:protocol Equatable { static func ==(lhs: Self, rhs: Self) -> Bool }
原创
This was discussed on the swift-evolution list recently (2016-01-31 through 2016-02-09 so far).以下是 Chris Lattner 所说的关于在结构或类范围内声明运算符的内容:
Yep, this is a generally desirable feature (at least for symmetric operators). This would also be great to get dynamic dispatch of operators within class declarations. I don’t think we have a firm proposal nailing down how name lookup works with this though.
后来(回复 Haravikk):
What are the name lookup issues? Do you mean cases where an operator for Foo == Foo exists in more than one location?
是的。名称查找必须具有明确定义的搜索顺序,这 定义阴影和无效的多重定义规则。
Personally I’d just stick with what we have now, i.e- treat operator implementations within a specific class/struct as being globally defined anyway and throw an error if the same signature is declared more than once.
我们需要多个模块来定义一个实例 运算符,我们需要扩展中的运算符,我们需要追溯 与任何其他成员一样遵守工作。
关于ios - 为什么必须将协议(protocol)运算符实现为全局函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35246003/