Index Invalidation in subscript

I think (albeit hesitantly) that MutableCollection semantically requires indices to remain valid.

  1. Without it, swapAt(Index, Index) doesn’t even make sense. How would you perform two separate insertions without the first invalidating the second?

  2. The documentation seems to imply it under “Conforming to the MutableCollection Protocol”:

    A value stored into a subscript of a MutableCollection instance must subsequently be accessible at that same position. That is, for a mutable collection instance a, index i, and value x, the two sets of assignments in the following code sample must be equivalent:

    a[i] = x
    let y = a[i]
    
    // Must be equivalent to:
    a[i] = x
    let y = x
    

    Technically that only actually means that a mutation must not invalidate the same index that described the mutation, but in most real use cases that would be the very index that needs invalidation first (e.g. overwriting a base letter with a combining character in a String would break the above condition even if String indices were plain Integers).

  3. See the following tangent in another thread, interspersed with other stuff, but starting about here:

I agree it would be helpful if the documentation stated it plainly one way or the other.

4 Likes