[swift-evolution] It's the little things..
David Sweeris
davesweeris at mac.com
Wed Dec 14 13:08:22 CST 2016
> On Dec 14, 2016, at 09:54, Jordan Rose <jordan_rose at apple.com> wrote:
>
>
>>> On Dec 13, 2016, at 20:43, David Sweeris via swift-evolution <swift-evolution at swift.org> wrote:
>>>
>>>
>>> On Dec 13, 2016, at 9:51 AM, Chris Lattner <clattner at apple.com> wrote:
>>>
>>> On Dec 12, 2016, at 6:58 PM, David Sweeris via swift-evolution <swift-evolution at swift.org> wrote:
>>>>> On Dec 12, 2016, at 16:15, John Holdsworth via swift-evolution <swift-evolution at swift.org> 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.
>> I don’t think that’s an issue in the stdlib, because `Optional` doesn’t conform to `Hashable` and, AFAIK, no other stdlib types conform to `ExpressibleByNilLiteral`. Custom types could conform to both, though, and according to a playground, that does indeed lead to some confusing code:
>> struct Foo : ExpressibleByNilLiteral, Hashable {...}
>> extension Dictionary { subscript(_ key:Key?) -> Value? { return key != nil ? self[key!] : nil } }
>> var bar = [Foo:Int]()
>> bar[nil] //calls `Foo.init(nilLiteral:())`, and tries to look up the new `Foo` in `bar` using the stdlib's subscript
>> bar[nil as Foo?] //passes `Optional<Foo>.none, which uses the extension's subscript
>
> I wouldn't be surprised if there's a proposal to make Optional conditionally conform to Hashable if/when we get conditional conformances.
Probably, yeah... I'll be curious as to how they propose we prevent collisions between Optional<T>.none.hashValue and any given T's hash value.
- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161214/1f2af029/attachment.html>
More information about the swift-evolution
mailing list