Proposal: Add Safe Subquence Access Via subscript For ColloctionType

Thank you, Brent; that captures the rationale exactly. The one thing missing is the performance piece: allowing arrays to do anything other than abort on out-of-range accesses would make them non-competitive with C arrays.

HTH,
-Dave

···

On Dec 14, 2015, at 6:13 PM, Brent Royal-Gordon via swift-evolution <swift-evolution@swift.org> wrote:

As a closing thought, subscripting hashes returns an optional value. You might consider this a pretty big inconsistency with arrays. Let me flip your argument against optional array subscripting, for dictionaries: When you are performing a subscript where the key is out of the key set, is it not a programmer error?

The use cases for arrays and dictionaries are different, though.

I’d say about 80% of the time you subscript an array, you’re using an index that was somehow derived *from* the array—for instance, a range like `0..<array.count`, or `array.indices`, or `array[indexPath.row]` where `tableView(_:numberOfRowsInSection:)` returns `array.count`. This is very different from dictionaries, where the key is usually some piece of data from somewhere *else* and you’re trying to look up the value corresponding to it. You rarely say, for instance, `array[2]` or `array[someRandomNumberFromSomewhere]`, but `dictionary[“myKey”]` or `dictionary[someRandomValueFromSomewhere]` are pretty common.

Because the use cases are different, arrays have a non-optional subscriptor which fails a precondition when the index is invalid, while dictionaries have an optional subscriptor which returns nil when the index is invalid.