Swift 中的自定义密钥失败

Custom key failure in Swift

我正在尝试使用自定义 class 作为 NSDictionary 中的键。为此,根据编译器,我需要实现 NSCopying 协议。我遵循 的建议,但它似乎不起作用。这是我的代码:

我的协议我的密钥 class 符合:

// My custom protocol
protocol TestProtocol: NSCopying {
    func testFunc()
}

当我实施 NSCopying 协议以 class 返回自身时,一切似乎都正常工作:

// Custom key class
class KeyClass: NSObject, TestProtocol {
    func testFunc() {
    }

    func copyWithZone(zone: NSZone) -> AnyObject {
        return self
    }
}

现在调用代码时:

    let key = KeyClass()
    let dictionary = NSMutableDictionary()

    dictionary.setObject("TestString", forKey: key)

    let value = dictionary[key]

值包含 "TestString"

但是当我从另一个堆栈主题将 KeyClass 实现更改为此时:

class KeyClass: NSObject, TestProtocol {
    func testFunc() {
    }

    required override init() {
    }

    required init(_ model: KeyClass) {
    }

    func copyWithZone(zone: NSZone) -> AnyObject {
        return self.dynamicType.init(self)
    }
}

我的值变量一直为零。谁能向我解释为什么上面的实现不起作用?

我猜协议继承者不适用于 OC 对象。所以尝试 swift 像 [KeyClass:String] 这样的字典或者不继承任何协议。