简体   繁体   中英

What is the correct behaviour of endIndex of array in Swift?

The endIndex returns the same values as count. Is it a correct behaviour or a bug?

var ar = [1, 2, 3, 4]
ar.count // 4
ar.endIndex // 4

count is the number of items in the collection, whereas endIndex is the Index (from the Indexable protocol) which is just past the end of the collection.

For Array , these are the same. For some other collections, such as ArraySlice , they are not:

let array = ["a", "b", "c", "d", "e"]

array.startIndex  // 0
array.count       // 5
array.endIndex    // 5

let slice = array[1..<4]  // elements are "b", "c", "d"

slice.startIndex  // 1
slice.count       // 3
slice.endIndex    // 4

Array.endIndex is meant to be the 1 past the end of the array (or the same as count) for iteration purposes, not subscripting.

let x = [1, 2, 3, 4]
for var i = x.startIndex; i < x.endIndex; i++ {
    println(x[i])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM