swiftuicoloroptional-variables

Optional Chaining or ternary expression in Swift?


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.


Solution

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