I have a type that collects weak references, which you can iterate over and append to. I want it to conform to
RangeReplaceableCollection, but I don't think I can do anything more specific than
The type itself is a classic pointer-length-capacity triplet, where the pointer is to a buffer of weak references. Once
length == capacity, before trying to realloc, it scans the buffer for nils that it can drop out. It only performs a reallocation if it can't remove enough nils to make room for the new elements.
The problem with conforming it to
Collection is, of all things,
subscript(_:). If the index type is just the index into the buffer, other threads could cause the weak reference to drop out from under you, and so indices could become invalid without apparent mutations to the collection.
I can think of two ways to fix this, neither of which is satisfying.
The first is to make the index type also hold a strong reference to the object. I guess this works, but I'm worried it's liable to produce footguns, when users don't realize they're holding a strong reference through the index.
The second is to make the element type
T? instead of
T. This is misleading since the
Iterator skips nils, but it would make the subscript implementable.
The third option, I suppose, is to implement many (but not all) of the collection operations without actually conforming to the protocol. I'm worried this is what I'll have to do, unless I can justify one of the other two behaviors. Is there a way I can implement the protocol without changing the semantics of the type?