【问题标题】:Type does not conform to an undefined protocol类型不符合未定义的协议
【发布时间】:2014-07-10 02:46:58
【问题描述】:

在 Xcode 6 Beta 2 中,我编写了以下类:

class Item : Printable, Hashable {
    var description:String {
     return "..."
    }
    var hashValue:Int {
        return 1
    }
}

我收到一条错误消息,指出“项目”类型不符合“Equatable”协议,即使我没有尝试实现名为“Equatable”的协议。有没有人见过这样的行为?任何解决方案或解决方法?谢谢!

【问题讨论】:

    标签: ios swift xcode6


    【解决方案1】:

    根据the Hashable docs:(请参阅该页面的最底部)

    符合 Hashable 协议的类型必须提供一个称为 hashValue 的可获取 Int 属性,还必须提供“等于”运算符 (==) 的实现。

    根据the Equatable docs,您可以通过为== 定义一个运算符重载函数来做到这一点,其中您想要的类型位于运算符的每一侧。

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

    这意味着你的代码是这样的:

    class Item : Printable, Hashable {
        var description:String {
            return "..."
        }
        var hashValue:Int {
            return 1
        }
    }
    
    func == (lhs: Item, rhs: Item) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
    
    // Testing...
    Item() == Item() //-> true
    

    当然,假设 hashValue 是您认为会使它们等效的东西。

    【讨论】:

    • 为什么不能只遵循 Equatable 协议,然后使用lhs.hashValue == rhs.hashValue 实现?
    【解决方案2】:

    Hashable 协议实现了Equatable 协议,这就是编译器报错的原因

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-23
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      相关资源
      最近更新 更多