[swift-evolution] [Pitch] Adding safety to arrays

Dave Abrahams dabrahams at apple.com
Sun Apr 16 00:51:48 CDT 2017


on Thu Apr 13 2017, David Sweeris <swift-evolution at swift.org> wrote:

>> On Apr 13, 2017, at 3:56 AM, Andrew Hart via swift-evolution
> <swift-evolution at swift.org> wrote:
>> 
>> Recently I’ve been considering the lack of safety around array indexes. Swift is designed with
> safety in mind, so this example would not compile:
>> 
>> var myString: String? = “hello”
>
>> myString.append(“ world!”)
>> 
>> The string is optional, not guaranteed to exist, so the last line requires a “!” to force-unwrap it.
>> 
>> 
>> 
>>     public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
>>         let section = self.sections[section]
>>         
>>         return section.items.count
>>     }
>> 
>> In this example, we could provide a section number that goes beyond the bounds of the self.sections array, without any warning.
>> 
>> My suggestion is perhaps arrays should by default return an optional when given an index, and of course they’d support forced-unwrapping too. So you could then do this:
>> 
>>     let section = self.sections[section]
>>     if section == nil {
>>         return 0
>>     } else {
>>         return section!.items.count
>>     }
>> 
>> Or you could do this:
>> 
>>     let section = self.sections[section]!
>>     
>>     return section.items.count
>> 
>> Of course this would be less convenient in a lot of cases, but this is the 1 place where apps seem
> to encounter a crash, crashing for the same reason that’s especially avoided across most of the rest
> of Swift.
>
> My understanding is that we need the current behavior to meet
> performance goals. We’ve discussed adding a “safe” subscript before,
> but the discussion usually fizzles out when no clear winner for the
> argument label emerges.

Also, please don't use the word “safe” this way around here as it
conflicts with the definition used by Swift.  As defined by Swift,
safety has nothing to do with whether something might trap or whether
it's spelled with a "!", but about whether it can corrupt memory, and by
that measure, Array (aside from withUnsafe[Mutable]BufferPointer and
passing it to functions taking Unsafe[Mutable]Pointer) is totally safe.

-- 
-Dave



More information about the swift-evolution mailing list