[swift-evolution] ? suffix for <, >, <=, >= comparisons with optionals to prevent subtle bugs
Al Skipp
al_skipp at fastmail.fm
Thu Dec 10 12:48:40 CST 2015
Just to add further salt, (or perhaps more appropriately, sugar) to optional chaining, it's not just map, it’s also flatMap, as and when required. Here’s a very silly example demonstrating it:
enum Hat { case Cap, Stetson, Helmet }
struct Pet { let age: Int, hat: Hat? } // a pet might wear a hat?!
struct Person { let name: String, pet: Pet? }
let p = Person(name: "Burt", pet: Pet(age: 10, hat: .Stetson))
(p.pet?.hat).dynamicType // Optional<Hat>.Type
p.pet.map { $0.hat }.dynamicType // Optional<Optional<Hat>>.Type
p.pet.flatMap { $0.hat }.dynamicType // Optional<Hat>.Type
This topic is going somewhat off-piste, so I’ll stop now!
Al
> On 10 Dec 2015, at 18:40, thorsten at portableinnovations.de wrote:
>
> Interesting stuff indeed!
>
>> Am 10.12.2015 um 19:21 schrieb Al Skipp <al_skipp at fastmail.fm <mailto:al_skipp at fastmail.fm>>:
>>
>> Interesting stuff!
>>
>> It did confuse me too, as I was expecting your initial code sample to work. My understanding is that ‘?’ is syntactic sugar for ‘map’ in this context. Anything following the ‘?’ is inside the Optional context.
>
> That is a great insight! Of course, ?. is map! That does make sense! And using parentheses to mark the end of the Optional context introduced by ?. makes sense, too.
>
> Thanks, Greg and Al!
>
> -Thorsten
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151210/2e2f1a05/attachment.html>
More information about the swift-evolution
mailing list