[swift-evolution] switch must be exhaustive, consider adding a default clause

Joe Groff jgroff at apple.com
Wed Apr 12 15:17:45 CDT 2017


> On Apr 11, 2017, at 11:24 AM, Drew Crawford <drew at drewcrawfordapps.com> wrote:
> 
> 
> 
> 
> On April 11, 2017 at 11:38:05 AM, Joe Groff (jgroff at apple.com <mailto:jgroff at apple.com>) wrote:
> 
>> By design, Swift avoids making semantic rules based on that kind of analysis, since it would be brittle and difficult to describe when the compiler can and can't see that a condition holds nonlocally like this.
> 
> Swift *currently implements* semantic rules based on this kind of analysis.  Exhibit A:
> 
> func foo() {
> 
>     let a: Bool
> 
>     if UUID().uuidString == "non-local condition" {
> 
>         a = true
> 
>     }
> 
>     else {
> 
>         preconditionFailure("Don't initialize a")
> 
>     }
> 
>     print("\(a)") //NOT: error: a is uninitialized
> 
> }
> 
That analysis is pretty strictly limited as well. The DI assignment has to happen once along every code path before the variable is ever read or escaped, so the effects are localized. To do pattern matching refinement something like you're proposing, we need to know that the value isn't mutated between switches. That becomes impossible if the variable is ever escaped, so you'd get spooky action at a distance where referencing the variable in a closure somewhere would cause seemingly-unrelated control flow errors to spring up seeming randomly; global variables and class properties would also fundamentally never benefit from this analysis, making it feel inconsistent when exactly the refined switch is allowed.

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170412/f7eeb378/attachment.html>


More information about the swift-evolution mailing list