[swift-evolution] Optional safe subscripting for arrays

Thorsten Seitz tseitz42 at icloud.com
Sat Feb 6 15:21:16 CST 2016


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>:
> 
> 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]"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160206/5cbf62e0/attachment.html>


More information about the swift-evolution mailing list