[swift-evolution] guard let x = x

Erica Sadun erica at ericasadun.com
Fri Oct 28 18:45:54 CDT 2016


> On Oct 28, 2016, at 5:00 PM, Huon Wilson <huon at apple.com> wrote:
> 
> 
>> On Oct 28, 2016, at 15:34, Erica Sadun via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>  <https://gist.github.com/erica/db9ce92b3d23cb20799460f603c0ae7c#detailed-design>Detailed Design
>> 
>> unwrap can be used with any one-value enumeration. The unwrapped value is bound to the same symbol as the associated type.
>> 
>> enum TypeName<T, U> { case anycase(T), anothercase(U) }
>> 
>> // First and second are type `TypeName`
>> let first = TypeName.anyCase(value1)
>> let second = TypeName. anothercase(value2)
>> 
>> guard unwrap first else { ... }
>> // first is now shadowed as type T
>> 
>> guard unwrap second else { ... }
>> // second is now shadowed as type U
>>  <https://gist.github.com/erica/db9ce92b3d23cb20799460f603c0ae7c#impact-on-existing-code>
> How does the compiler decide whether to succeed on anycase or succeed on anothercase respectively? In general, the compiler only statically knows that first & second are of type TypeName, not anything about which case (they could be passed in as function parameters, or returned by an opaque function e.g. `let x = OtherLibrary.returnsTypeName(); guard unwrap x else { … }`), and thus the variant to unwrap has to be chosen based only on that piece of information.
> 
> It seems to me that doing this either has to be restricted to enums with an “obvious” choice for unwrapping, like Optional, or rely on a sort of forward-looking type inference that Swift doesn’t currently use to deduce the unwrapped type based on how the value is used later (and I’m not sure that works in all cases, e.g. what if T == U for the TypeName example).

It succeeds on any one-item case and fails on any non-item case.

-- E


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161028/7c110eeb/attachment.html>


More information about the swift-evolution mailing list