简体   繁体   中英

Type does not conform to an undefined protocol

In Xcode 6 Beta 2 I have written the following class:

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

I am receiving an error stating that the Type 'Item' does not conform to the protocol 'Equatable' even though I have not tried to implement a protocol called 'Equatable.' Has anyone seen behavior like this? Any solution or workaround? thanks!

According to the Hashable docs: (see the very bottom of that page)

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 (==).

And according to the Equatable docs you do that by defining an operator overload function for == where the type you want is on each side of the operator.

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

Which means your code something like this:

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

Assuming hashValue is what you think would make them equivalent, of course.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM