And it works fine. The above code isn’t getting the first element of an Array, it’s getting the first element of an ArraySlice. Different thing. If you want an Array, you can wrap whatever you have in
With that said, I should clarify that I totally understand where you’re coming from. Lots of users have a trajectory into Swift where they enter the language, pick up
Array as the first collection they use, and instantly subscript it. This appears to work, so they are not forced to understand Swift’s
In many ways, the real mistake was to make
Int. This was done because Swift had no notion of offset-based indexing (and indeed still does not, though it’s in progress: see Offset Indexing and Slicing). If
Index were opaque, it would force users to confront their understanding of what the system actually does.
And the system is defined sensibly.
Index is not intended to be a convenient type for the user, it’s intended to be a convenient type for the
Collection. The goal of
Collection.Index is, roughly, if you have one you should be able to subscript
Collection with it and get the element in
Int is fine. But for other
Collections we use other types.
Dictionary uses an opaque type that ends up holding an offset into the
CircularBuffer does a similar thing. You can construct weird
Collections over things like the
getaddrinfo list by making the
Index type a pointer.
This solution is very flexible, but without offset-based indexing it bumps into the confusion boundary for many users very quickly. The Swift community really ought to push offset-based indexing over the line to help avoid these problems.