Currently, Swift does not provide a built-in way to safely access elements by index. I would like to propose adding a method or subscript, similar to Array.prototype.at() - JavaScript | MDN.
This proposal has 2 main features:
Return an optional value
Access an element from the end if index is negative
In Swift, the existing subscript(index: Int) -> Element { get set } (subscript(_:) | Apple Developer Documentation) will trigger a runtime crash if the index is out of bounds.
The proposed at(_ index: Int) -> Element? { get } method would return an optional value, making it a safer and more convenient alternative for index-based access.
Returning optional values is discussed enough in other threads and seems like it's not convincing enough, so this proposal focuses on accessing elements from the end if index is negative.
This one is different to others in regards of using negative indices to indicate offsets from the end (if I got your idea right)! Quite interesting idea. If to consider that at all, I'd also consider setters. We don't have null_resettable in Swift but optional could work here (with some agreement whether array[relativeIndex: -2] = nil means removal of the second to last element of the array or something else).
Yes, accessing elements from the end is indicated if the index is negative just like JS Array.prototype.at().
I am not a contributor of Swift lang, so I wanna defer to someone with more knowledge, but I didn't think about setters because there are more cases to handle, and it could be more complicated. However, if it's reasonable and straightforward to add setters, I'd love to have both getters and setters.
Perhaps, returning an optional value is discussed enough in other threads and seems like it's not convincing enough, so this proposal focuses on accessing elements from the end if index is negative. Then getters/setters more makes sense. I modified the original post.