paretoDev
paretoDev

Reputation: 13

swift) In the for loop, even iterating the last index, referencing .index(after: index) does not make an error ? why?

var a = "hi my name is Jim."

for index in a.indices {
    var rightAfterIndex = a.index(after: index)
}

In the code above, at the end of the for-loop, I will definitely be iterating the last index of the swift String, but still, referencing the index after the last index does not make an error. Why does that happen?

Upvotes: 0

Views: 37

Answers (1)

vadian
vadian

Reputation: 285160

The index after the last item of indices is the (valid) endIndex of the string.

a.index(after: a.indices.last!) == a.endIndex // true

From the documentation:

A string’s “past the end” position—that is, the position one greater than the last valid subscript argument.

Upvotes: 0

Related Questions