[swift-evolution] Proposal: Optional Binding Shorthand Syntax

Sean Heber sean at fifthace.com
Thu Dec 3 21:13:16 CST 2015


What about lifting the whole concept out of "if" or "guard" and making a new construct that directly communicates the intent?

For example:

when foo { ... }

Which could be combined with "where" to generate an if-like construct:

when foo where foo.isSomething { ... }

Inside the code block, you can access foo directly and it isn't shadowed - so if it was a var, it is mutable, etc.

l8r
Sean


> On Dec 3, 2015, at 8:25 PM, David Waite <david at alkaline-solutions.com> wrote:
> 
> 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
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151203/6a96e180/attachment.html>


More information about the swift-evolution mailing list