不能使用NSObjet子类作为快速字典中的键

问题描述 投票:0回答:1

我有这堂课:

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
swift dictionary nsobject
1个回答
0
投票
尝试删除下面的重载运算符,

static func == (lhs: NSObjectObject, rhs: NSObjectObject) -> Bool { return lhs.hashValue == rhs.hashValue }

© www.soinside.com 2019 - 2024. All rights reserved.