rmh rmh - 15 days ago 5
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")


Per: http://nshipster.com/nshashtable-and-nsmaptable/

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'"
error.

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

CRD CRD
Answer

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")
Comments