[swift-evolution] Enums and Source Compatibility

Kenny Leung kenny_leung at pobox.com
Mon Sep 18 13:24:29 CDT 2017


Ah, I get it now. Even if the switch knows what to do with the unknown value, the rest of your code would have to know what to do with it, and that is unlikely.

-Kenny


> On Sep 18, 2017, at 10:23 AM, Jordan Rose <jordan_rose at apple.com> wrote:
> 
> 
> 
>> On Sep 16, 2017, at 15:35, Kenny Leung via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>> In general, I agree with everything in the proposal.
>> 
>> I’d like to propose these alternative extensions for clients:
>> 
>> 1) As a client of an enum, I’d like to know in the future when a new value has been added to an enum, since I may have to do something about it. How about adding the “exhaustive” keyword to be used in the switch statement? Like
>> 
>> exhaustive switch excuse {
>>     case eatenByPet:
>>         // …
>>     case thoughtItWasDueNextWeek:
>>         // …
>>     default:
>>         // …
>> }
>> 
>> If exhaustive is used, there would be a warning if all cases aren’t covered *even though default exists*. This means that I as the client thought I had everything covered when I wrote this code.
>> 
>> As already mentioned, this makes the default case un-testable, which brings me to
>> 
>> 2) All non-exhaustive enums should have the pseudo value “default” that can be used just like a regular value. This would allow you to write code like:
>> 
>> teacher.failedToHandInHomework(excuse: .default)
>> 
>> which would allow you to trip the default case in any code you may write.
> 
> Brent came up with this idea as well, but after thinking it through Joe Groff and I found that it doesn't really work in practice:
> 
>> It’s going to be very common to have a future value and hand it right back to the framework without looking at it, for example:
>> 
>> override func process(_ transaction: @testable Transaction) {
>>   switch transaction {
>>   case .deposit(let amount):
>>     // …
>>   case .withdrawal(let amount):
>>     // …
>>   default:
>>     super.process(transaction) // hmm…
>>   }
>> }
>> 
>> So just making it to the ‘default’ case doesn’t guarantee that it’s testable in practice.
> 
> I'll add the actual code here to the "Testing invalid cases" section under "Alternatives considered", since that's a clearer example than the paragraph I wrote. (Oh, and the "exhaustive switch" is equivalent to the section on "'future' cases".)
> 
> Thanks for the feedback!
> Jordan

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170918/9a48c2a8/attachment.html>


More information about the swift-evolution mailing list