[swift-evolution] Proposal: Weak Native Swift Containers
rileytestut at gmail.com
Thu Dec 10 19:08:09 CST 2015
I'm not sure how NSHashTable and NSMapTable are implemented under the hood, but assumedly the native Swift implementation would be somewhat similar. I'm not opposed to figuring out the best way to accomplish this, but if it's already been implemented and works well, no use going through all that work again :-)
I agree they should be distinct types, but I'm debating how explicit that should be to the user. On one hand, there could be a "WeakSet" or "WeakDictionary" type, that is completely separate, explicit, and public, or we could go a more "magical" route and have a private implementation of Set/Dictionary that conforms to all the same protocols as Set/Dictionary (similar to the different implementations of Array depending on what the backing store is), and is used when a weak set is needed.
Or, it could be in the middle, and we could convert a Set/Dictionary into a weak variant, such as by accessing a ".weak" property (akin to the ".lazy" property implemented by CollectionType). I think all these solutions have their pros and cons, and it would be worth discussing the best way to approach this problem.
> On Dec 10, 2015, at 4:53 PM, Greg Parker <gparker at apple.com> wrote:
>> On Dec 10, 2015, at 2:55 PM, Riley Testut via swift-evolution <swift-evolution at swift.org> wrote:
>> I think native swift collections with support for weak references for their contents would be very useful, and in more places than just listed above. I don’t think Array could be easily extended to support it (what happens if a value is released? does everything shift down? do they keep their indices?), but Set and Dictionary (where the keys and/or values could be weak, akin to NSMapTable) would be good candidates IMO.
> Containers of weak references are valuable, but I suspect they will need to be completely distinct from Array and Set and Dictionary. The problem is that a weak reference can become nil at any time. This subverts the value semantics of Swift's current containers and defeats assumptions that typical container algorithms make. (For example, a typical sorting algorithm assumes that comparison results between two elements are consistent over time, but that isn't true if a weak reference disappears while a sort is in progress.)
> Note that Foundation does not support weak references in NSDictionary or NSSet.
> Greg Parker gparker at apple.com Runtime Wrangler
More information about the swift-evolution