Yes, the idea was to key off of an optional index. something like this:
> extension Array {
> public subscript(_ index: Int?) -> Element? {
> guard let i = index, i < endIndex else { return nil }
>
> return self[i]
> }
> }
>
> let array = ["foo", "bar", "baz"]
>
> array[1] // "bar"
>
> let index: Int? = 5
> let notInArray = array[index]
This doesn’t work today with the error “ambiguous use of 'subscript’” on
“self[i]” but surely that could be fixed.
Jeff Kelley
[email protected] | @SlaunchaMan <https://twitter.com/SlaunchaMan> |
jeffkelley.org <http://jeffkelley.org/>
> On Apr 13, 2017, at 12:18 PM, David Sweeris <[email protected]> wrote:
>
>
>> On Apr 13, 2017, at 08:53, Josh Parmenter <[email protected]> wrote:
>>
>> This seems inconsistent to me. 2 is 2... 2 itself is not optional. You
>> wouldn't expect 2 to be unwrapped.
>
> Correct. I think the idea was that "2?" would get converted to an
> `Optional<Int>`, which would then call a subscript that took an `Index?`
> instead of `Index`. The trailing "?" doesn't do that, but for some reason I
> thought it might.
>
> IMHO, the semantics are clear(ish) in context, but it feels slightly odd for
> "?" to have two opposite behaviors depending on whether the argument is or
> isn't an Optional.
>
> In any case, given that we're discussing a "safe subscript", we need a way to
> differentiate the safe subscript from the unsafe subscript. The only two ways
> to do that are to either add an argument label or change the argument type,
> and IMHO the best alternate argument type is `Index?`, since it's pretty
> light-weight, already part of the stdlib, and already familiar to Swift
> developers.
>
> Someone already said it was a bad idea, though, so I'm rethinking my support.
>
> - Dave Sweeris
>
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution