Let's say I have a some objects representing network connections. Once these connections are disconnected, the associated objects disappear. I don't want to hang on to a connection object which is no longer connected.
I also want to associate some data with these connections using a dictionary. So I might have the code:
class Connection { ... }
class Metadata { ... }
var metadata: [Connection: Metadata] = [:]
But the above code means that the dictionary will keep references to the Connection
objects which I don't want. I'd prefer to have the associated entries be removed, ideally automatically, when the Connection
objects disappear.
So I tried:
var metadata: [weak Connection: Metadata] = [:]
But this doesn't work. What is a good alternative solution to this?
NSMapTable
andNSHashTable
does not exist on Linux, so you'll need to use an approach like Rob's answer. – Alodie