Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Chaining or ternary expression in Swift? [duplicate]

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.

like image 891
Armstrongest Avatar asked Oct 27 '25 08:10

Armstrongest


1 Answers

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

like image 54
Antonio Avatar answered Oct 30 '25 12:10

Antonio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!