我如何使用类作为字典键?
例
class Base:NSObject{}
class A:Base{}
class B:Base{}
var map:[NSObject:AnyObject] = [:]
map[A.self] = "lalala";
更新,发现一些转换.它有效,但我无法解释.
let any: AnyObject = A.self as AnyObject;
let key = any as! NSObject;
print(key.hash);
最佳答案 我认为你的问题是A.self将不会是一个NSObject.将字典定义更改为[AnyObject:AnyObject]将失败,因为AnyObject不可清除.您可以使用NSObject的可散列类方法之一,例如.描述…
class Base:NSObject{}
class A:Base{}
class B:Base{}
var map:[NSObject:AnyObject] = [:] // A.self in Swift will not be an NSObject
//var map:[AnyObject:AnyObject] = [:]// AnyObject does not conform to Hashable
map[A.description()] = "lalala"
let c = map[A.description()] // "lalala"
//map[A.self] = "lalala" // Cannot subscript [NSObject : AnyObject] with index A.Type