The code sample you just posted should not work that way and as I mentioned in my first post in this thread I'd be strongly against it. Furthermore doing something like this would be a catastrophic source breaking change.
I do not like adding a direct subscript overload to Collection
, because subscripts are not discoverable. Adding a simple view type (similar to what a Slice
is) can provide additional information and makes it not only more convenient to use but also extensible for the future.
In your example the there is also a typo:
-> Element?
^
// should be just or you'll return `Element??` otherwise
-> Element
Also you are using a failable subscript as it was optional chaining. It was not my intention to pitch it like that. init?
does not work like that, so shouldn't subscript?
, or it will become ambiguous at some point.
The failable subscript would not make any sense if we're not going to allow the setter, because otherwise you simply don't need a failable subscript anymore. However if you have a failable subscript you can conditionally create a settable but failable subscript on the view type which is statically type safe and eliminates the issue with assigning a nil
to a non-nil index of a mutable collection (which is a no-op).
struct SomeView<T> where T : Collection {
// Since it potentially can fail, the return type is
// automatically wrapped into an Optional.
subscript?(index: T.Index) -> T.Element {
get { ... }
}
}
extension SomeView where T : MutableCollection {
// The getter is similar to the get-only behavior for
// a simple collection. However the setter requires
// statically the user to provide `T.Element` not
// `T.Element?`.
subscript?(index: T.Index) -> T.Element {
get { ... }
set { ... }
}
}
I think something like this would be by far a superior solution to this general problem. I also assume that such a view type will most likely play well with some of the concepts from the Ownership manifesto.
That said, I don't want to bombard this thread with simply a vision of mine. If you want a simpler solution, go for it, but I'd probably be against it during the review, because I don't think it's worth it in the long term. 
P.S.: A small tip, there exists an equivalent to isValidIndex
already which avoids the noise of manually verifying the index bounds.
// If `true` it's safe to access the collection with the given index.
collection.indices.contains(yourIndex)