view raw
rmh rmh - 6 months ago 82
Swift Question

How can I use NSMapTable with String keys in Swift 3?

In earlier versions of Swift, it was possible to have the keys in my NSMapTable be strings:

let mapTable = NSMapTable(keyOptions: .StrongMemory, valueOptions: .WeakMemory)
mapTable.setObject(..., forKey: "foo")


In Swift 3, NSMapTable needs generic parameters. But when I try to do:

NSMapTable<String, MyClass>(keyOptions: .strongMemory, valueOptions: .weakMemory)

I get a
"Type 'String' does not conform to protocol 'AnyObject'"

What is the correct way to have the keys of my NSMapTable be strings in Swift 3?


I wouldn't say your own answer was a "hack", just more general than needed, use:

NSMapTable<NSString, MyClass>(keyOptions: .strongMemory, valueOptions: .weakMemory)
mapTable.setObject(..., forKey: "foo")