If let syntactic sugar


(Massimo Frasson) #1

Hi everyone,

I find myself writing a lot of times "if let” to unwrap optional values. In particular I do as follows:

var something: Type?

func foo() -> Void {
  if let something = something {
    doStuff(something) //just an example
  }
}

As you can see I usually keep the same variable name and the variable scoping does the rest.
I think it could be a cool syntactic sugar getting the same result as the code above omitting “something =“.
Let me be more clear: if you don’t specify the name of the unwrapped variable, swift does the unwrapping for you, keeping the same variable name.

So the code above would be:

var something: Type?

func foo() -> Void {
  if let something {
    doStuff(something)
  }
}

Let me know what you think and also if you have questions.

Best regards,
Massimo Frasson
iOS Developer, Belka srl


(Craig Cruden) #2

Ceylon does something like that - but it is more readable / understandable IMHO.

It uses “if exists something” and then something inside the scope of the if is unwrapped for use. No new variable, it reads almost exactly as it is.

···

So the code above would be:

var something: Type?

func foo() -> Void {
if let something {
   doStuff(something)
}
}

Let me know what you think and also if you have questions.

Best regards,
Massimo Frasson
iOS Developer, Belka srl
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


(Taras Zakharko) #3

There are two (or even three) active discussions about this very topic :wink:

— Taras

···

On 04 Feb 2016, at 16:22, Craig Cruden via swift-evolution <swift-evolution@swift.org> wrote:

Ceylon does something like that - but it is more readable / understandable IMHO.

It uses “if exists something” and then something inside the scope of the if is unwrapped for use. No new variable, it reads almost exactly as it is.

So the code above would be:

var something: Type?

func foo() -> Void {
if let something {
  doStuff(something)
}
}

Let me know what you think and also if you have questions.

Best regards,
Massimo Frasson
iOS Developer, Belka srl
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution