If there is a bit class that contains CGPoint
the type of point attribute, the class is defined as follows
class Bit { var point : CGPoint init(point : CGPoint) { self.point = point }}
Question: How do I compare bits? The answer: Hashable
the implementation of the Protocol is possible, and Hashable
in fact need to implement the Equatable
protocol
1. Implement Hashable
When you add Hashable
a protocol to a class, the Xcode compilation is thrown "Type ‘Bit‘ does not conform to protocol ‘Hashable‘
. Command+click Click Hashable
Definition will find the following code:
protocol Hashable : Equatable { /// Returns the hash value. The hash value is not guaranteed to be stable /// across different invocations of the same program. Do not persist the hash /// value across program runs. var hashValue: Int { get }}
We need to implement the HashValue property getter
, it is known that the string type is implemented Hashable
(the string type can be directly compared, sort), so you can use the string to implement getter, the following code:
var hashValue : Int { get { return "\(self.point.x),\(self.point.y)".hashValue }}
Add code and find the compiler still error "Type ‘Bit‘ does not conform to protocol ‘Equatable‘"
-no protocol implemented Equatable
.
2. Implement Equatable
Commend+click Click on hashable definition, enter and then click the Equatable protocol definition, you can see the following definition:
protocol Equatable { func ==(lhs: Self, rhs: Self) -> Bool}
We will find that the Equatable protocol needs to implement a function, the ==
function, so how do we actually implement it?
First, we use the Getter return value hashable to do the comparison, the function implementation code is as follows:
func ==(lhs: Bit, rhs: Bit) -> Bool { return lhs.hashValue == rhs.hashValue}
The above is actually implementing the overloaded operator ==
in the following code, we found that 2 point can be directly compared between.
The final code is as follows
Playground-how to implement Hashable and equatableImportUIKitMARK:-equatableFunc = = (LHS:Bit, RHS:Bit)Bool {return lhs.hashvalue = = Rhs.hashvalue}ClassBit:hashable {var point:CgpointMARK:-Hashablevar hashValue:Int {get {Return"\(Self.point.x),\ (self.point.y) ". HashValue}} //mark:-Bit init (point: CGPoint) { Span class= "Hljs-keyword" >self.point = Point}}var point_a_1_0 = Bit (point: cgpoint (x: 1, y: 0)) var point_b_1_0 = bit (point: CGPoint (x: 1, y: 0)) var point_c_0_1 = bit (point: cgpoint (x: 0, y: 1)) Point_a_1_0 = = Point_b_1_0point_a_1_0 = = point_c_0_1
The above code is passed in the XCode6 GM test.
Original: Http://www.swiftcoder.info/dev/codefellows/2014/8/2/how-to-implement-hashable-for-your-custom-class
Swift Custom class implementation hashable