On Dec 12, 2016, at 6:58 PM, David Sweeris via swift-evolution 
<[email protected]> wrote:
>> On Dec 12, 2016, at 16:15, John Holdsworth via swift-evolution 
>> <[email protected]> wrote:
>> 
>> I’d like to raise again the idea of optionality when referencing a key or
>> calling a function could be possible using a ? i.e instead of
>> 
>>   let a = key != nil ? dict[key] : nil
>> 
>> you could just write:
>> 
>>   let a = dict[key?]
>> 
>> or even 
>> 
>>   let a = func( arg: argumentThatMayBeNull? ) // not called if argument is 
>> nil
> 
> The first part is pretty easy to add in an extension:
> 
> extension Dictionary {
>    subscript(_ key:Key?) -> Value? {
>        return key != nil ? self[key!] : nil
>    }
> }
> 
> At least I think that works... I'm on my phone so I can't test it.

You can do something like this, but I’d recommend labeling the subscript.  The 
problem comes up when you have a dictionary that has an optional key:   When 
you use “myDict[nil]”, you may get one or the other, but you probably mean one 
specifically.  

Using a label on the subscript solves this, and makes the code more explicit 
that you’re not just getting the normal subscript that everyone would expect.

-Chris
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to