[swift-evolution] guard let x = x

Erica Sadun erica at ericasadun.com
Fri Oct 28 19:22:32 CDT 2016


> 
> On Oct 28, 2016, at 5:55 PM, Kevin Nattinger <swift at nattinger.net> wrote:
> 
>> 
>> On Oct 28, 2016, at 4:45 PM, Erica Sadun via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>> 
>>> On Oct 28, 2016, at 5:00 PM, Huon Wilson <huon at apple.com <mailto: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.
> 
> I think he meant this:
> 
> enum TypeName<T, U> { case anycase(T), anothercase(U) }
> 
> func foo<T, U>(instance: TypeName<T, U>) {
> 	guard unwrap instance else { ... }
> }
> 
> What type does instance have? 

Fair enough. How about: An unwrappable enumeration must have at most one generic type so the compiler can guarantee at compile time that the type is unambiguous if the unwrapping succeeds

-- E

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


More information about the swift-evolution mailing list