[swift-evolution] Proposal Sketch: simplify optional unwrapping syntax

Chris Lattner clattner at apple.com
Sat Dec 19 11:09:14 CST 2015


> On Dec 11, 2015, at 8:11 AM, Daniel Hooper via swift-evolution <swift-evolution at swift.org> wrote:
> 
> A very common pattern in swift code is to "guard let" or "if let" optionals  - this works by creating a new non-optional variable to be used by future code. Often, the new variable is given the same name as the original optional variable, creating a shadow variable. This approach leads to odd looking code like this:
> 
> if let nearestX = nearestX { closest = nearestX }
> guard let layer = layer else { continue } 
> // use layer
> 
> At a glance, and to Swift newcomers, this code looks completely non-sensical. It's also verbose for simply ensuring the variable is non-nil. 
> 
> The solution:
> Swift should generate unwrapped shadow variables after nil checking. The compiler would treat the below code as if it had created an unwrapped shadow variable.

Hi Daniel,

We discussed this extensively (and for a while this was plan of record to implement) but it has some pretty significant challenges.  The main problem is that it makes it extremely unclear and unpredictable what the type of a variable is.  One of the primary reasons we constrain type inference to a statement boundary to is to make it more clear what is going on.  You don’t have “spooky type action at a distance” like you do in some other languages with whole-function type inference.

Type confusion is particularly problematic here because the different cases you have depending on what T? is:

- With something like Int?, there are many operations that make sense on Int but not on Int?
- With something like [Int]?, there are operations (like map) that make sense on both types.
- Some operations are completely common between the two (e.g. “let x = v”).

Further, swift has an implicit promotion from T to T?, which can cause extremely confusing downstream errors if you’re not aware of what is going on.  There are also implementation concerns as well.

-Chris




More information about the swift-evolution mailing list