safe subscript via a Collection extension that returns Element? using indices.contains(index) ? self[index] : nil. This lets you use optional binding like if let item = array[safe: index] { ... } without crashing.Why this happens
Swift arrays deliberately crash on out-of-bounds access rather than returning nil. This is a design choice by the Swift team: if subscripts returned optionals, every array access would require unwrapping, even when the index is known to be valid. The language prioritizes performance and ergonomics for the common case (valid indices) over safety for the rare case (invalid indices).
When you write array[3] on a three-element array, you get EXC_BAD_INSTRUCTION (a runtime trap). There is no built-in optional-returning subscript on Array or Collection.
How to fix it
1. Add a safe subscript via a Collection extension (recommended)
The cleanest, most reusable solution is to extend Collection with a labeled subscript that returns an optional element. This works on arrays, slices, and any other collection type.
extension Collection {
/// Returns the element at `index` if it is within bounds, otherwise `nil`.
subscript(safe index: Index) -> Element? {
indices.contains(index) ? self[index] : nil
}
}
Usage:
let fruits = ["Apple", "Banana", "Coconut"]
if let fruit = fruits[safe: 3] {
print(fruit) // not executed
} else {
print("Index out of bounds") // prints this
}
// Works in loops too
for i in -2...5 {
if let item = fruits[safe: i] {
print(item)
}
}
The label safe: makes the call site explicit and avoids clashing with the existing subscript.
2. Use a standalone helper function
If you prefer not to extend Collection globally, a free function keeps the same logic scoped to your module or file.
func safeElement<C: Collection>(_ collection: C, at index: C.Index) -> C.Element? {
collection.indices.contains(index) ? collection[index] : nil
}
Usage:
let numbers = [10, 20, 30]
if let value = safeElement(numbers, at: 5) {
print(value)
}
3. Wrap the array in a custom type (for domain-specific APIs)
When you control the data model, a wrapper type can expose only safe access.
struct SafeArray<Element> {
private var storage: [Element] = []
subscript(safe index: Int) -> Element? {
storage.indices.contains(index) ? storage[index] : nil
}
mutating func append(_ element: Element) { storage.append(element) }
var count: Int { storage.count }
}
This approach is useful when you want to enforce safe access throughout a codebase without relying on developers remembering the safe: label.
How to prevent it
- Adopt the
Collectionextension in a shared utility module so it’s available project-wide. - Use the
safe:label consistently; code review can flag raw subscript usage on indices that aren’t statically proven valid. - Prefer higher-level APIs (
first,last,prefix,suffix,dropFirst,dropLast) when the index is derived from the collection’s own bounds. - Enable Swift’s runtime checks (they’re on by default in debug builds) — the trap is intentional and catches logic errors early.
FAQ
Does the safe subscript work with String and Dictionary?
Yes. Because it extends Collection, it works on any type conforming to Collection, including String (indices are String.Index), ArraySlice, Set (though Set has no meaningful order), and Dictionary (indices are Dictionary.Index, not keys). For key-based lookup on Dictionary, use the built-in subscript which already returns Value?.
Is there a performance cost?
The indices.contains(index) check is O(1) for random-access collections like Array and ContiguousArray. For bidirectional or forward-only collections it may be O(n), but the subscript itself is already O(n) in those cases. In release builds the overhead is negligible.
Can I make the standard subscript return an optional instead?
No. Overriding the existing unlabeled subscript would break the Swift standard library’s contract and every piece of code that expects a non-optional return. The labeled subscript (safe:) is the intended extension point.
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.