Skip to content

/errors/swift/index-out-of-range

Swift Fatal error: Index out of range

The commands on this page have not been executed by our verification runner yet.updated
tool
Swift
versions
Swift 5.x – 6.x
os
macos, linux, windows

Fatal error: Index out of range is a Swift run-time crash: the code subscripted an array with an index outside 0..<count. Swift checks every array subscript and stops the program rather than reading invalid memory. The usual causes are an off-by-one loop (0...array.count), an empty array, or an index computed before elements were removed. Loop over array.indices or the elements themselves, and use first, last or an explicit bounds check when the index may be invalid.

Example

swift
let scores = [90, 72, 85]
for i in 0...scores.count {      // closed range: i reaches 3
    print(scores[i])             // Fatal error: Index out of range when i == 3
}

Fixes

swift
let scores = [90, 72, 85]

for score in scores { print(score) }                     // no index at all
for (i, score) in scores.enumerated() { print(i, score) }
for i in scores.indices { print(scores[i]) }             // always valid indices
for i in 0..<scores.count { print(scores[i]) }           // half-open range

let top = scores.first ?? 0                              // empty-safe
let i = 5
if scores.indices.contains(i) { print(scores[i]) }

extension Collection {
    subscript(safe index: Index) -> Element? {           // returns nil instead of crashing
        indices.contains(index) ? self[index] : nil
    }
}
print(scores[safe: 5] ?? "none")
MessageCause
Fatal error: Index out of rangeArray subscript outside 0..<count
Fatal error: Can't remove last element from an empty collectionremoveLast() on an empty array
Fatal error: Unexpectedly found nil while unwrapping an Optional valueForce-unwrapping nil with !

Sources