Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Functions in Swift Functions in Swift Functions in Code

Kanish Chhabra
Kanish Chhabra
2,151 Points

Nil-Coalescing Operator

What is "Nil-Coalescing Operator"? I read this in the book published by apple on 'swift' but I wasn't able to understand it.

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

The nil coalescing operator (?? in code) returns the value on the value on the left if it's not nil, or the value on the right if it is nil, like this:

var first = "one"
let second = "two"

let test = first ?? second
// test is "one"

first = nil

let otherTest = first ?? second
// otherTest is "second"

This is especially useful for setting default values, like in functions where you otherwise can't or shouldn't, like this:

func someFunction(param: String?) -> Void{
    // arg is a non-optional String. It contains what was passed into param if it wasn't nil, or "Example" otherwise
    var arg = param ?? "Example"

    // The rest of the function's code goes here
}