ios - 为什么必须将协议(protocol)运算符实现为全局函数?

标签 ios swift equatable

我已经看到了这个 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 declared static:

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/

相关文章:

ios - 在“init”中初始化的对象无法在“viewDidLoad”中访问

ios - 如何在 swift 中使用 ObjectMapper 将值从 String 向下舍入为 Double

ios - 在 Swift 3 中发布 JSON 请求

iOS - 同步保存到 UserDefaults 吗?

swift - 如何在类层次结构中正确实现 Equatable 协议(protocol)?

ios - 代码符号想要使用钥匙串(keychain)中的 key 进行签名

ios - 使用 ALAssetLibrary 获取照片库中图像的时间戳

ios - 在特定单元格添加一个部分

flutter - Equatable 的子类将什么传递给 super (Equatable 类)?

Swift:类型符合 Equatable 的泛型数组