ios - 类型不符合未定义的协议(protocol)

标签 ios swift xcode6

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

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

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

最佳答案

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

Types that conform to the Hashable protocol must provide a gettable Int property called hashValue, and must also provide an implementation of the “is equal” operator (==).

并根据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 是您认为会使它们等价的值。

关于ios - 类型不符合未定义的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24661096/

相关文章:

ios - 在导航栏和状态栏上设置渐变

ios - 在 Safari 中打开 UIWebView 之外的目标 ="_blank"链接

ios - runUntilDate 在后台线程上不起作用

ios - PrepareforSegue 函数从未运行,附加 View Controller 中的变量为空

ios - Swift 元组作为字典值

ios - Swift - 'AnyObject!' 不能转换为 'ViewController' ;您的意思是使用 'as!' 强制向下转换吗?

ios - 将平移手势识别器限制为特定圆圈

ios - 在 Swift 3.0 上登录 Facebook 时出现错误代码 2500

ios - swift IOS : How to download image using NSURLSession and didReciveData?

ios - 添加新记录的核心数据错误