[swift-users] array.first vs. array[0]
Jordan Rose
jordan_rose at apple.com
Wed Jan 20 12:11:04 CST 2016
> On Jan 16, 2016, at 15:07, David Turnbull via swift-users <swift-users at swift.org> wrote:
>
> On Sat, Jan 16, 2016 at 2:46 PM, Adriano Ferreira via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> wrote:
> Isn’t the subscript supposed to return an optional as well?
>
> Not arrays. They stop your program when out of bounds.
>
For the record, this isn't a difference between arrays and other collections. All Collections return a non-optional value when subscripted by an Index, with the assumption that you shouldn't be putting random indexes into a collection unless they came from that collection in the first place, or have been already validated in some way. With 'first', on the other hand, it's very convenient to be able to say "collection.first ?? defaultValue".
"But what about dictionaries?" Ah, but a dictionary key is not an Index (note the capital). The relation between a Collection and an Index is that there must be a constant-time operation to get to a value from an Index. There's a separate DictionaryIndex that represents a position in a dictionary for that purpose.
Jordan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160120/70a7e6ff/attachment.html>
More information about the swift-users
mailing list