The reason it crashes is because getting an element from an array using a subscript does not return an optional. If no element exists at the index it simply crashes with index out of bounds. This is in contrast to dictionaries where subscript access returns an optional. The rationale behind this design decision is that, for arrays, unwrapping the optional every time would be a right pain, especially as all you have to do is test the index is in 0 ..< array.count
.
Your guard statement tries to access an array element that does not exist, so it crashes. Also, your guard statement is the wrong way around. The block after the else is what is executed in the exceptional condition.
So, if you use empty_array.first
which does return an optional, you should do this:
guard let first = empty_array.first else { return /* bail out of the function */ }
doSomething(with: first) // first is unwrapped here.
Or use if
if let first = empty_array.first
{
doSomething(with: first) // first is unwrapped here.
}
Or you can test the index to make sure it is in range. Has the advantage of working with any index, not just zero
let index = // Some integer
guard index >= 0 && index < empty_array.count else { return }
doSomething(with: empty_array[index])
Or
guard (0 ..< empty_array.count).contains(index) else { return }