1

One thing that originally discouraged me from incorporating too much optional binding in my code was the addition of more variable names. For example, I'd generally write:

if bananasInBarrel != nil{
  print("We have \(bananasInBarrel!) bananas in the barrel.")
}

Because the alternative seemed to get a bit messy:

if let safeBananas = bananasInBarrel{
  print("We have \(safeBananas) bananas in the barrel.")
}

That's a lot of bananas. I've seen people use something like b as the new variable name (which could get hard-to-read in a larger block of code), but I'm wondering if there's a generally accepted standard for the style of variable name to use with optional binding? Thanks for reading.

Rogare
  • 3,234
  • 3
  • 27
  • 50
  • i would say the generally accepted standard is the one with the if let rather than the != nil.. I would say it's what it fits most of you and won't make that much of a real life differences.PS: This is not optional chaining. – Korpel Oct 17 '15 at 12:12
  • Hey, yes I'm converting to the `if let` approach for safer code, but was wondering about naming conventions for the new variable to ease readability. It can get messy! – Rogare Oct 17 '15 at 12:13
  • 1
    `if let ... ` is optional *binding*, not optional chaining. – Martin R Oct 17 '15 at 12:17
  • Yeah.It really can get messy but when i took some classes for swift or searched for some pro swift codes everyone was using the if let. It is kinda like the variable naming like myName. Swift things.In order to have optional chaining you need more than one optionals. If the last optional is nil then all the expression is nil – Korpel Oct 17 '15 at 12:17
  • @MartinR Yup, my mistake. Thanks for the correction. – Rogare Oct 17 '15 at 12:18
  • 2
    I don't think there is an accepted standard. But note that you can even use the same name: `if let bananasInBarrel = bananasInBarrel { ... }`, that creates a bananasInBarrel variable whose scope is the if-block. – Martin R Oct 17 '15 at 12:43
  • The answers to this question would be primarily opinion based. I personally despise `if let x = x` because it can lead to confusion for the reader of your code. You now have two `x` variables in your code, one is an optional and the other isn't. I know one of the hardest things in programming is coming up with variable names. You could make your own convention like appending a `_u` for `unwrapped` such as `if let bananasInBarrel_u = bananasInBarrel`. At least it would be clear to the reader. – vacawama Oct 17 '15 at 14:15
  • OK, that's great. Thanks for the scope explanation, @MartinR, and that's a cool idea @vacawama—thanks! – Rogare Oct 17 '15 at 15:37

1 Answers1

5

Just use the same name:

if let bananasInBarrel = bananasInBarrel {
  print("We have \(bananasInBarrel) bananas in the barrel.")
}

Don't use hungarian notation - the compiler will complain if you are using an unwrapped optional.