Safe access to array elements in Swift: how to avoid Index out of range?
Hello everyone! I just started learning Swift and encountered a problem. When I access an array element by index, for example:
```swift
let numbers = [10, 20, 30]
let value = numbers[5]
```
The app crashes with an `Index out of range` error. This happens when I try to get an element that doesn't exist in the array. I understand that I need to check the bounds, but how to do it correctly and elegantly? In other languages, I'm used to methods like `getOrNull`, but Swift doesn't have that.
I tried writing checks manually:
```swift
if index >= 0 && index < numbers.count {
let value = numbers[index]
} else {
// error handling
}
```
But this looks cumbersome, especially when there are many such accesses. Is there a built-in way in Swift to safely access array elements that would re
No answers yet.
Log in to leave an answer