Search code examples
swiftoption-typeoptional-binding

Naming convention for optional binding


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.


Solution

  • 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.