无法将NSObject子类用作Swift字典中的键

时间:2019-11-19 12:41:02

标签: swift dictionary nsobject

我上了这个课:

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失败:(“ nil”)不等于(“” Optional(“ obj1”)“)

此外,打印语句的输出为:

obj1 => -406393155368168228
obj2 => -3721711324458125961
obj1Copy => -406393155368168228

0 个答案:

没有答案