Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type does not conform to an undefined protocol

Tags:

ios

swift

xcode6

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!

like image 654
Pheepster Avatar asked Mar 20 '23 02:03

Pheepster


1 Answers

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.

like image 132
Alex Wayne Avatar answered Mar 28 '23 13:03

Alex Wayne