Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class as dictionary key in swift

Tags:

swift

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);
like image 965
john07 Avatar asked Oct 19 '22 02:10

john07


1 Answers

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
like image 199
Grimxn Avatar answered Jan 04 '23 05:01

Grimxn