[swift-evolution] Proposal: Optional Binding Shorthand Syntax

David Waite david at alkaline-solutions.com
Thu Dec 3 20:25:21 CST 2015


I might argue that if let is already an odd case; people often read it equivalent to "if (let x=x)”, but “let x=x” has completely different behavior outside the context of an if let statement (I in fact had to try it before I realized it does, in fact, work). Obviously, 'let x=x’ on its own could not have the same behavior.

In that spirit, I propose an alternative feature:

if foo? { … }

where the variable is not shadowed by a copy - instead, inside the block it behaves as an implicit unwrapped optional, including keeping any mutability.

so for example:

 func foo(x:Int?) { 
     if var x = x { // var so it can be assigned
         x++ 
     } 
     print(x) 
 } 

foo(1) // => 1, updating the aliased x does not do anything

# working code in Swift 1.2
 func bar(x:Int?) { 
     var y=x 
     if let x=x { 
         y=x+1 
     } 
     print(y) 
 } 
bar(1) # => Optional(2)

# proposed
func proposed(x:Int?) {
     var y = x // since swift 3 won't have var function arguments
     if y? { // var so it can be assigned
         y++ 
     } 
     print(y) 
 } 

proposed(1) // => Optional(2)

-DW

> On Dec 3, 2015, at 3:42 PM, Chris Lattner <clattner at apple.com> wrote:
> 
> 
> “if let foo {“ is a frequently proposed extension to the syntax, but it is not one that we’re likely to ever add.
> 
> I agree that this is a common pattern, and it would allow you to “write less code”, but that isn’t the goal of Swift.  Since code is read more often than it is written, the real goal behind Swift is to let you write “more readable code” by eliminating boilerplate and other noise. 
> 
> Reducing syntax isn’t itself a goal, particularly if the result could/would be confusing for someone who has to read and maintain your code later.
> 
> -Chris

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151203/ca68b90b/attachment-0001.html>


More information about the swift-evolution mailing list