Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

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 
like image 790
Kostiantyn Koval Avatar asked Jul 20 '14 17:07

Kostiantyn Koval


People also ask

What is endIndex in Swift?

In Swift, the endIndex property is used to get a past-the-end position. This means that the position one is greater than the last valid subscript argument. If the string is empty, it returns startIndex .

What is the datatype of array in Swift?

The type of a Swift array is written in full as Array<Element> , where Element is the type of values the array is allowed to store. You can also write the type of an array in shorthand form as [Element] .

How do I get the size of an array in Swift?

Swift – Array Size To get the size of an array in Swift, use count function on the array. Following is a quick example to get the count of elements present in the array. array_name is the array variable name. count returns an integer value for the size of this array.

Are arrays in Swift dynamic?

Swift arrays come in two flavors: dynamic and static.


1 Answers

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 
like image 173
jtbandes Avatar answered Oct 11 '22 13:10

jtbandes