Add accessor with bounds check to Array

Oh, boy. This again. This comes up a lot. A casual search turned up some threads. There were probably more, but I really didn't feel like scrolling that far down.

A list of discussions on "safe" array indexing.

The tl;dr here is that safe does not mean, "does not crash." It means "don't silently propagate invalid data", which can be accomplished here by either crashing or returning nil. As out of bounds indexing is a logic error, crashing is appropriate.

Returning nil has two problems:

  • it makes using arrays very awkward.
  • it's not appropriate in a generic context. The only way to get a bad index from a generic collection is if you kept an invalidated index around (or worse, used an index from a different collection of the same type), which is a logic error that you really want to catch early.

That said, there are some niche cases for this (like using an array instead of a Dictionary<Int, Element>), but those would be better handled by a new type that wraps an array, rather than directly using an array. So, while there's nothing wrong with giving array an at(_:) method or a second labled subscript, I don't think it's really worth putting in the standard library.

4 Likes