[Draft] Adding Safe indexing to Array

Since @Jens brought this up anyway: I've been thinking for a while that an alternate conceptual approach would be to think of a new Array subscript as a key lookup, along the lines of a dictionary. Since the parameter type conflicts with the standard subscript, it has to be a keyword, but perhaps it could be:

  array [key: i]

or:

  array [lookup: i]

However…

There's yet another possible direction, which is to stop thinking of the parameter as an index (valid or invalid), but rather as an offset from the start of the array, which kind of links this thread up with this other thread: Shorthand for Offsetting startIndex and endIndex.

The various suggestions in that thread are mostly about slicing, so don't necessarily propose a single-argument lookup method/subscript, and those that do provide a non-optional result. I suppose they could have an optional result instead, since this is not a vital case in that proposal.

The advantage would be a single, consistent keyword convention (whether method or array), that "explains" the optional return type in terms of a semantic difference in the parameter type (index vs. offset), even though both types are Int for an array.

The optional result doesn't quite "sit" naturally in that thread, but I don't see all that much consensus emerging in this thread. A joint solution might be more palatable.


Edit: To clarify (since that thread is long), the idea would be to define a "complete" API set on Sequence (the first 2) or Collection (the 3rd one):

func index (offset: Int) -> Collection.Index?
func element (offset: Int) -> Collection.Element?
subscript (offset offset: Int) -> Collection.Element?

(with a keyword TBD in place of offset).

1 Like