[swift-evolution] [Review] SE-0117: Default classes to benon-subclassable publicly

Rod Brown rodney.brown6 at icloud.com
Tue Jul 12 03:10:41 CDT 2016

> On 12 Jul 2016, at 4:53 PM, Tino Heth via swift-evolution <swift-evolution at swift.org> wrote:
>>> Safety is valued, but Swift cares (and should care!) about pragmatism as well… the most obvious example that comes to my mind are arrays, which have no safeguards that stop you from accessing elements that aren't there.
>> I'm not sure I understand this point. First, a guaranteed runtime trap on an out-of-bounds index is a *massive* safety improvement over what we had in C/C++/Objective-C.
> … but still, it wouldn't it be much safer to return an optional?\


This argument comes up often, but I side with some of the smartest people in the industry who say the safest thing to do is actually crash, just like Swift does in this case.

If you are accessing an element in an array that doesn’t exist, you didn’t reason about the contents of said array correctly. Therefore, whatever you were planning to do, something in your logic is seriously wrong. It’s safer to say “Stop!” at this stage, rather than let you proceed further into the bug infested mess you’re about to walk into. Other side effects might occur, both in your model code, and you may also be leaving your UI in a completely random and inconsistent state. Flow on effects could even include deleting incorrect files from disk if you’re using the array to store file URLs, and because you don’t know your indexes correctly, you’re risking deleting the wrong file.

Experience has shown that it is safer to bring your software to a very abrupt stop rather than hope you can handle this situation. After all… you clearly don’t know about your current state, so how can you know how to correctly recover from it?

From what I understand, this was the Core Team’s reasoning for not returning optionals from array indexes, and I support that decision.

As an aside, I actually do have my own personal “ifExists:” subscript that runs the correct checks and returns an optional. I have specific use cases for it where it does make sense. But I can see the danger of including something like that in the Standard Library. It’s a rare case, and would open up the can of worms when everyone starts using it, instead of actually correctly reasoning about their code.

- Rod

More information about the swift-evolution mailing list