The idea of a failable subscript is quite intriguing, but I think you haven't nailed the semantics here. Failable initializer will fail if the type cannot be constructed and optional functions (Obj-C) will return the result type wrapped into an Optional
if the function is not implemented.
In that sense a failable subscripts would only allow you to assign the same type as declared after the arrow, but could silently fail. The getter however will always wrap the type into an Optional
. This is a different feature which we don't have, but it could be worth exploring and it would at least be able to merge the subscript version of this pitch nicely.
public subscript?(checked position: Index) -> Element {
// ^ pay attention to the `?` here!
get {
guard indices ~= position else { return nil }
return self[position] // will still return `Element?`
}
set {
// Replace value in-place
guard indices ~= position else { return }
self[position] = newValue // newValue is of type `Element`
}
}