[swift-evolution] Add ability to validate collection indices

Dave Abrahams dabrahams at apple.com
Sun Dec 18 21:08:36 CST 2016


on Fri Dec 16 2016, Alexey Komnin <swift-evolution at swift.org> wrote:

> Hello everyone!
>
> Currently, indices of a collection might be invalidated due to call to
> any mutating method of the object. Assume, you have two indices - they
> point to the first and the last elements of an array -   and you call
> removeLast() routine. The latter index would be invalidated during
> this call but the first one is not. It's understandable.
>
> Now imagine, you've got two indices of type SetIndex<T>. You don't
> know what elements of the Set they point to. Then you call remove()
> routine. Which of indices would still be valid?
>
> Here is the complete example:
>
>     var testSet: Set = [1, 2, 3, 4, 5]
>
>     let idx = testSet.index(of: 4)!
>     print("value at index \(idx): \(testSet[idx])")
>
>     testSet.remove(3)
>     print("value at index \(idx): \(testSet[idx])")
>     // fatal error: attempting to access Set elements using an invalid Index
>
> The reference states that indices may become invalid as a result of
> mutating operations, but it doesn't state which of indices.

Yes.  This is something we've been meaning to better nail down.  There
are also index relationships we want to ensure between collections and
their copies and slices.

> The proposed solution is: define new method for Collection protocol to
> make it possible to validate index before subscripting particular
> collection:
>     validate(index: Self.Index)

I don't see how that really helps programmers.  What they need most is
the ability to reason about index validity, IMO.

> What do you think? I feel, like we should discuss it before I
> formalize it as a proposal.
> Thanks.
>
> - Alexey Komnin
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-- 
-Dave



More information about the swift-evolution mailing list