4

Is there a more efficient, readable or more modern way of writing the following?

let currentColor:UIColor = view.backgroundColor != nil 
  ? view.backgroundColor! // forced unwrapping
  : UIColor.whiteColor() // fallback value

I don't mind using a ternary operator here, but it feels like I should be using the Swift if let currentColor = view.backgroundColor syntax. I'm just not sure how that would look to specify a default value.

Armstrongest
  • 15,181
  • 13
  • 67
  • 106
  • 1
    Is it pure coincidence that the questions are so similar? An almost identical question has been asked (and answered) two hours ago. – Martin R Oct 03 '14 at 18:46
  • @MartinR Hilarious... I searched but didn't find a quick answer. Fascinating. I wonder if it has to do with the TeamTreehouse course that has a random number generator lesson in it applying to color. – Armstrongest Oct 03 '14 at 18:53
  • Reading that Q/A now... yeah pretty much the same. If you searched using google, maybe it was not indexed yet :) – Antonio Oct 03 '14 at 18:53
  • @MartinR Indeed, I was surprised to realize it was a different person. – Alex Wayne Oct 03 '14 at 18:53
  • What's even funnier is that one my top voted question is on using the Null coalescing operator `??` in C# several years ago. http://stackoverflow.com/questions/278703/unique-ways-to-use-the-null-coalescing-operator Glad to see this in Swift. – Armstrongest Oct 03 '14 at 18:57

1 Answers1

13

You can use the nil coalescing operator:

let currentColor: UIColor = view.backgroundColor ?? UIColor.whiteColor()

If view.backgroundColor is not nil, it is used for the assignment, otherwise what comes to the right of ??

Antonio
  • 71,651
  • 11
  • 148
  • 165