我有这堂课:
class NSObjectObject: NSObject {
let important: String
let notImportant: String
init(important: String, notImportant: String) {
self.important = important
self.notImportant = notImportant
}
static func == (lhs: NSObjectObject, rhs: NSObjectObject) -> Bool {
return lhs.hashValue == rhs.hashValue
}
override var hash: Int {
return important.hashValue
}
}
而且我已经进行了此测试:
class HashTests: XCTestCase {
func testNSObjectObject() {
var dict = [NSObjectObject: String]()
let obj1 = NSObjectObject(important: "A", notImportant: "B")
let obj2 = NSObjectObject(important: "C", notImportant: "D")
dict[obj1] = "obj1"
dict[obj2] = "obj2"
let obj1Copy = NSObjectObject(important: "A", notImportant: "B")
print("obj1 => \(obj1.hashValue)")
print("obj2 => \(obj2.hashValue)")
print("obj1Copy => \(obj1Copy.hashValue)")
XCTAssertEqual(dict[obj1Copy], "obj1")
}
}
哪个失败XCTAssertEqual failed: ("nil") is not equal to ("Optional("obj1")")
此外,打印语句的输出是:
obj1 => -406393155368168228
obj2 => -3721711324458125961
obj1Copy => -406393155368168228
static func == (lhs: NSObjectObject, rhs: NSObjectObject) -> Bool {
return lhs.hashValue == rhs.hashValue
}