[swift-evolution] Optional safe subscripting for arrays
Thorsten Seitz
tseitz42 at icloud.com
Fri Feb 5 14:54:04 CST 2016
> Am 05.02.2016 um 10:20 schrieb Haravikk via swift-evolution <swift-evolution at swift.org>:
>
>
>> 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 ;)
You are right, of course!
Actually the code as written above already works exactly like that (I just tried on IBM's Swift sandbox): if the second index is out of bounds, the value won't get changed, otherwise it will be changed and the new value will be nil if the array did contain nil at the position of the second index.
-Thorsten
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160205/c79fea1d/attachment.html>
More information about the swift-evolution
mailing list