Swift Struct 不符合协议(protocol) Equatable?

标签 swift struct protocols equatable

如何使结构符合协议(protocol)“Equatable”?

我正在使用 Xcode 7.3.1

struct MyStruct {
   var id: Int
   var value: String

   init(id: Int, value: String) {
       self.id = id
       self.value = value
   }

   var description: String {
       return "blablabla"
   }

}

当我使用“MyStruct”时,Xcode 显示错误:

MyStruct does not conform to protocol "Equatable"

你有没有让 MyStruct 符合协议(protocol)的想法?

最佳答案

Swift 4.1(及更高版本)更新的答案:

从 Swift 4.1 开始,您所要做的就是遵守 Equatable协议(protocol)而不需要实现 == 方法。请参阅:SE-0185 - Synthesizing Equatable and Hashable conformance .

例子:

struct MyStruct: Equatable {
    var id: Int
    var value: String
}

let obj1 = MyStruct(id: 101, value: "object")
let obj2 = MyStruct(id: 101, value: "object")

obj1 == obj2 // true


请记住 == 的默认行为是比较所有 类型属性(基于示例:lhs. id == rhs.id && lhs.value == rhs.value).如果你的目标是实现自定义行为(例如只比较一个属性),你必须自己做:

struct MyStruct: Equatable {
    var id: Int
    var value: String
}

extension MyStruct {
    static func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
        return lhs.id == rhs.id
    }
}

let obj1 = MyStruct(id: 101, value: "obj1")
let obj2 = MyStruct(id: 101, value: "obj2")

obj1 == obj2 // true

此时,相等性将基于id 值,而不管value 的值是多少。

关于Swift Struct 不符合协议(protocol) Equatable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37541512/

相关文章:

c# - 用于解析的可扩展类型安全枚举类?

protocols - smb协议(protocol)漏洞解决方案

ios - 使用 UILayoutGuide 设置 UICollectionViewCell 中 UILabel 的垂直位置

swift - NSCollectionView : How to prevent right click selection?

swift - 如何使用排序正确显示可读性强的输出?

c++ - 从结构转换为浮点*

C 如何从结构中建立结构

swift - 用于 JSON 请求的 AlamoFire 异步完成处理程序

xcode - 无法让自定义类在 SpriteKit 场景中工作(swiftui 和 xcode beta)

swift - 使用协议(protocol)和关联类型的强类型树层次结构