Indices & Bounds

Swift Arrays: Indices & Bounds

Arrays have startIndex and endIndex (one past last).

Use indices to loop valid positions.

Out-of-bounds access crashes at runtime.


Valid Indices

Use indices to visit only valid positions.

Example

let items = [10, 20, 30]
print(items.startIndex)       // 0
for i in items.indices {
  print("index: \(i), value: \(items[i])")
}

Valid subscript indices: 0..<items.count (zero up to, not including, count).

Example

let items = [10, 20, 30]
print(items[0])   // OK
// print(items[3]) // out of bounds

Use indices for index-and-value access without enumerated().

Note: endIndex is not a valid subscript. The last valid index is items.index(before: items.endIndex).



Last Valid Index

Get the last valid index with index(before: endIndex).

Example

let items = [10, 20, 30]
let lastIndex = items.index(before: items.endIndex)
print(lastIndex)        // 2
print(items[lastIndex]) // 30

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *