The documentation for
func index(after i: Index) -> Index states that:
i: A valid index of the collection.
imust be less than
It does not however state what should happen when the method is called with
endIndex. And there seem to be different kinds of behaviors depending on the exact collection type.
let string = "Hello, World!" let pastEndIndex = string.index(after: string.endIndex)
... causes a runtime error:
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION
On the other hand:
let array = [1, 2, 3, 4] let pastEndIndex = array.index(after: array.endIndex)
... executes without problems and even produces the "pseudo-correct" result that
pastEndIndex == 5.
To me this looks like undefined behavior, which we tend to avoid in Swift. I feel like
String's behavior is good, because it enforces the semantics of
index(after:) in a sensible way. And I think
Array's implementation should take the same approach of trapping on invalid inputs.
Any thoughts on this?