Junior — Middle
Does using the array element access operator provide protection against out-of-bounds access?
sobes.tech AI
Answer from AI
In Swift, the array element access operator (for example, array[index]) does not provide bounds checking. If the index is out of bounds, the application will throw a runtime error and crash.
To access elements safely, you can use methods that return an optional value, such as an extension with an index check:
extension Array {
func safeGet(index: Int) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
let arr = [1, 2, 3]
print(arr.safeGet(index: 5)) // nil, safe
Thus, the standard operator does not protect against out-of-bounds access, and the developer must manually check the bounds.