/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
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
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")Related crashes
| Message | Cause |
|---|---|
| Fatal error: Index out of range | Array subscript outside 0..<count |
| Fatal error: Can't remove last element from an empty collection | removeLast() on an empty array |
| Fatal error: Unexpectedly found nil while unwrapping an Optional value | Force-unwrapping nil with ! |
Sources
Related pages
errors · swiftSwift Fatal error: Unexpectedly found nil while unwrapping an Optional valueSwift crashes with this fatal error when ! force-unwraps an Optional that is nil, or an outlet is not connected. Use if let, guard let or ?? to handle nil.errors · swiftSwift error: Value of optional type 'String?' must be unwrapped to a value of type 'String'Swift will not use an Optional where a plain value is required. Unwrap it with if let or guard let, give a default with ??, or use optional chaining with ?.compare · swiftSwift struct vs class: value type or reference type?Swift structs are value types copied on assignment; classes are reference types shared between variables, with inheritance and identity. Prefer a struct.