Created
September 5, 2016 02:50
-
-
Save owenzhao/9f1201dee398b3a611a57b69bee5b589 to your computer and use it in GitHub Desktop.
\`==\`与\`hashValue`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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