[swift-evolution] Proposal: Add Safe Subquence Access Via subscript For ColloctionType
brent at architechies.com
Mon Dec 14 20:13:09 CST 2015
> 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` 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.
More information about the swift-evolution