Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...