类型不符合未定义的协议

时间:2014-07-09 18:20:05

标签: ios swift xcode6

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

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

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

2 个答案:

答案 0 :(得分:5)

根据the Hashable docs:(见该页面的最底部)

  

符合Hashable协议的类型必须提供名为hashValue,的gettable Int属性,并且还必须提供“is equal”运算符(==)的实现。

根据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是你认为会使它们等效的。

答案 1 :(得分:2)

Hashable协议实现Equatable协议,因此编译器抱怨的原因