Optional safe subscripting for arrays

There's a pretty big difference between "nil" and "Some(nil)" (and "Some(Some(1))"). This was covered pretty early on in the Apple Swift blog <Optionals Case Study: valuesForKeys - Swift Blog - Apple Developer; While double optionals can be confusing for humans, the compiler ought to pretty much always do something sensible.

…though I did say "ought to"; the compiler has done some less-than-sensible things in overload resolution before…

Jordan

···

On Feb 5, 2016, at 15:58, Maximilian Hünenberger via swift-evolution <swift-evolution@swift.org> wrote:

You are totally right. The return type is "Int??".

My point was that if we allowed something like this (as suggested by Dave Sweeris I think):

        var array: [Int?] = [1]
        array[ifExists: 0] = nil

To set the element at index 0 to nil instead of doing nothing.
The next example would also set index 0 to nil even though the getter failed:

         array[ifExists: 0] = array[ifExists: 1]

- Maximilian

Am 05.02.2016 um 10:20 schrieb Haravikk <swift-evolution@haravikk.me <mailto:swift-evolution@haravikk.me>>:

On 4 Feb 2016, at 20:24, Maximilian Hünenberger via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@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 ;)

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution