I like the smell of Swift in the morning…

Use the Nil Coalescing Operator in Swift to assign default values to properties

Posted: | Author: | Filed under: iOS, Objective-C, Swift | No Comments »

One of the new operators that comes with Swift is the Nil Coalescing Operator. In the documentation it is explained as: The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil.

This operator already exited in C but for Objective-C developers it is kind of new (more about that at the bottom of this post).

With this operator assigning values to a property with a fallback to a default value becomes really concise:

Instead of doing this:

func setupBackgroundColor(color: UIColor?) {
   if (color != nil) {
      backgroundColor = color
   } else {
      backgroundColor = UIColor.whiteColor()

You can simply do this:

func setupBackgroundColor(color: UIColor?) {
        backgroundColor = color ?? UIColor.whiteColor()

Pretty cool, isn’t it?

Actually something like this was already possible with Objective C:

- (void)setupBackgroundColor:(UIColor *)color {
   self.backgroundColor = color ? : [UIColor whiteColor];

Leave a Reply