How i can use class as dictionary key? example
class Base:NSObject{}
class A:Base{}
class B:Base{}
var map:[NSObject:AnyObject] = [:]
map[A.self] = "lalala";
update, found some conversion. It work, but I can't explain.
let any: AnyObject = A.self as AnyObject;
let key = any as! NSObject;
print(key.hash);
I think your problem is that A.self
will simply not be an NSObject
. Changing your dictionary definition to [AnyObject:AnyObject]
will fail because AnyObject
is not hashable. You could use one of NSObject
's hashable class methods, e.g. .description
...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With