[swift-users] array.first vs. array[0]

Dave Abrahams dabrahams at apple.com
Wed Jan 20 14:28:24 CST 2016


on Wed Jan 20 2016, Jordan Rose via swift-users <swift-users-AT-swift.org> wrote:

>> 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. 

Well, but that also applies to dictionary keys.  The difference is that
a sequence of consecutive indices can be used to access all the elements
of the collection.

-Dave



More information about the swift-users mailing list