[swift-evolution] Optional safe subscripting for arrays

davesweeris at mac.com davesweeris at mac.com
Sat Feb 6 17:50:56 CST 2016


In principle, I’m not opposed to that. In practice, though… unless you’re also proposing we give it “magic” syntax like what Optionals currently have, we’d have to manually wrap/unwrap the values:
bar[ifExists: 3] = Result.result(4)
print(bar[ifExists: 4].result)

Which would strictly speaking work, but IMHO is more annoying than just manually checking collection.indices.contains(idx) before attempting the subscript.

- Dave Sweeris

> On Feb 6, 2016, at 13:21, Thorsten Seitz via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Ah ok, I was using the other version which distinguishes between nil and Optional(nil):
> 
> 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! } }
>     }
> }
> 
> Where you can assign Optional(nil) to set a value to nil which is admittedly not very intuitive...
> 
> var array: [Int?] = [1]
> array[ifExists: 0] = Optional(nil)
> print(array) // "[nil]"
> array = [1]
> array[ifExists: 0] = array[ifExists: 1]
> print(array) // "[Optional(1)]"
> 
> A solution would probably be to introduce another enum mimicking Optional but built for the array subscript which allows to distinguish both cases.
> 
> -Thorsten 
> 
> Am 06.02.2016 um 21:52 schrieb Maximilian Hünenberger <m.huenenberger at me.com <mailto:m.huenenberger at me.com>>:
> 
>> var array: [Int?] = [1]
>> array[ifExists: 0] = nil // sets array[0] to nil if index is valid
>> print(array) // "[nil]"
>> array = [1]
>> array[ifExists: 0] = array[ifExists: 1]
>> print(array) // "[nil]"
> _______________________________________________
> 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/20160206/c8fd3414/attachment.html>


More information about the swift-evolution mailing list