[swift-evolution] Add ability to validate collection indices
Alexey Komnin
interfere.work at gmail.com
Fri Dec 16 07:56:39 CST 2016
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.
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)
What do you think? I feel, like we should discuss it before I
formalize it as a proposal.
Thanks.
- Alexey Komnin
More information about the swift-evolution
mailing list