Skip to content

Instantly share code, notes, and snippets.

@owenzhao
Created September 5, 2016 02:50
Show Gist options
  • Save owenzhao/9f1201dee398b3a611a57b69bee5b589 to your computer and use it in GitHub Desktop.
Save owenzhao/9f1201dee398b3a611a57b69bee5b589 to your computer and use it in GitHub Desktop.
\`==\`与\`hashValue`
class Fruit:Hashable {
let name:String
var hashValue: Int {
return name.hashValue
}
init(name:String) {
self.name = name
}
static func ==(lhs: Fruit, rhs: Fruit) -> Bool {
return type(of:lhs) == type(of:rhs) && lhs.name == rhs.name
}
}
class Apple:Fruit {
override var hashValue: Int {
return super.hashValue - "apple".characters.count
}
}
class Banana:Fruit {
override var hashValue: Int {
return super.hashValue - "banana".characters.count
}
}
let a = Apple(name: "")
let b = Banana(name: "")
print(a == b) // false
print(a.hashValue) // prints 4799450059485596700
print(b.hashValue) // prints 4799450059485596699
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment