[Draft] Adding Safe indexing to Array

This is very much not the reason. It is not about performance. Since bounds checks are still performed on subscript access, just to trap rather than decide on whether to return nil, that cost is going to be there regardless (though in many cases the optimizer can eliminate them).

The important piece elided from your guard example is: how was i generated? In the vast majority of straight-line code, i cannot possibly be outside the bounds, because it was generated from logic that ensures i is kept within the bounds.

In those cases, the failure case for the else is unreachable. It is meaningless, other than to swallow the error silently or trap or some compromise like assert in debug but silently fail in prod.

Now, you can take issue with a trap taking down the whole program – and it might perhaps be better in some future Swift if we can find some way of isolating and safely winding down rather than hard panicking. But the idea of forcing the user to unwrap every time – even in a for i in array.indices loop – is safety theatre not actual safety. Instead, the user will just wear out their ! key, and become so used to banging stuff that the one time they shouldn't, they will.

13 Likes