[swift-evolution] Arrays Returning Optionals instead of Index Out of Bounds
charlie at charliemonroe.net
Thu Jun 23 10:03:06 CDT 2016
> On Jun 23, 2016, at 4:52 PM, Andreas Ley via swift-evolution <swift-evolution at swift.org> wrote:
>> "..*most* people don’t expect.." could you prove this please?
> I should have written “most people I know” or “the people I work with".
>> Especially if they know a little of C language or other language that don't allow to use wrong indexes for arrays.
> Maybe that’s the point: They don’t. And it is my understanding that they shouldn’t need to; that Swift should be for everyone and a great language to get into programming.
>> This behavior described in help/documentation/tutorial for Swift, this is how Swift works with arrays.
> Yes, and I agree with you that people should read the documentation.
> However, the question is: Is this behavior optimal? Is a runtime error really the best way to handle this for the most common use case of arrays?
Yes. If you are reaching out of bounds of the array, there is a computation error (most likely) and the app is in an incosistent state and it's always better to crash than to pretend it's all OK and potentially do some harm to user's data.
If the getter returned an optional, most people would get annoyed really quickly and started just placing ! everywhere, which would make the code the same, without the diagnostic message which index was accessed.
There is only a handful of usecases where it is advantageous to have the behavior described and no one can stop you from creating an extension and adding an accessor method that returns an optional.
AFAIK I don't know any language that is as strongly typed as Swift whose default behavior would be allowing to reach our of the bounds without a runtime error.
> But the definition of “most common use case” varies wildly. Hence my idea to have separate classes for separate needs.
> In the end, what’s most important to me is to be able to have a consistent mental model. Something simple like: If I’m using classes called “unsafe” or exclamation marks, my app might experience runtime errors. That’s something the students I’ve taught could understand easily.
> - Andreas
> swift-evolution mailing list
> swift-evolution at swift.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-evolution