Naming convention for optional binding

北城以北 提交于 2020-02-12 02:42:46

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/33186448/naming-convention-for-optional-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!