[swift-evolution] Optional safe subscripting for arrays

Haravikk swift-evolution at haravikk.me
Fri Feb 5 03:20:26 CST 2016


> On 4 Feb 2016, at 20:24, Maximilian Hünenberger via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I just realized that the normal setter for failable lookups is very nice in case of assigning/swapping:
> 
>> extension Array {
>>     subscript(ifExists idx: Index) -> Element? {
>>         get { return (startIndex ..< endIndex) ~= idx ? self[idx] : nil }
>>         set { if (startIndex ..< endIndex) ~= idx && newValue != nil { self[idx] = newValue! } }
>>     }
>> }
> 
> 
>         // array[index1] is only set if both indexes are valid
>         array[ifExists: index1] = array[ifExists: index2] 
> 
> 
> if array is of type [Int?] and the special setter for optional Elements would have been added:
> 
> array[index1] would be set to "nil" if array[index2] is nil or index2 is not valid which is unfortunate.

Wouldn’t the return type be Int?? in this case? It’s not as pretty to test for as a plain Int? but iirc you can still distinguish a return type of nil from an optional that happens to contain nil, which should allow you to tell the difference between a nil value and an invalid index, I just can’t recall how at the moment (as I design around cases like these like my life depends on it ;)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160205/d48a8e7d/attachment.html>


More information about the swift-evolution mailing list