rmh rmh - 1 year ago 188
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'"

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

Answer Source

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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download