Menu
Coddy logo textTech

Nil Coalescing Operator

Part of the Fundamentals section of Coddy's Swift journey — lesson 14 of 86.

Sometimes you just want to provide a default value when an optional is nil, without writing multiple lines of code. Swift's nil coalescing operator (??) does exactly that — it unwraps an optional if it has a value, or returns a default value if it's nil.

let nickname: String? = nil
let displayName = nickname ?? "Guest"
print(displayName) // Guest

Since nickname is nil, the operator returns "Guest" instead. If nickname had a value, that value would be used.

let username: String? = "SwiftCoder"
let greeting = username ?? "Anonymous"
print(greeting) // SwiftCoder

The nil coalescing operator is perfect for one-liners where you need a fallback value. It's cleaner than writing an if let statement when you simply want to substitute nil with a default. The result is always a non-optional value, so you can use it directly without further unwrapping.

challenge icon

Challenge

Easy
Write a function getDisplayName that takes an optional username and a defaultName, then returns the appropriate display name using the nil coalescing operator.

If the username is empty (represented by an empty string ""), treat it as nil and return the default name. Otherwise, return the username.

Parameters:

  • username (String): The user's name (empty string represents nil)
  • defaultName (String): The fallback name to use

Returns: The username if it's not empty, otherwise the defaultName.

Hint: Convert the username to an optional inside your function — if it's empty, make it nil. Then use ?? to provide the fallback.

Cheat sheet

The nil coalescing operator (??) unwraps an optional if it has a value, or returns a default value if it's nil:

let nickname: String? = nil
let displayName = nickname ?? "Guest"
print(displayName) // Guest

If the optional has a value, that value is used instead:

let username: String? = "SwiftCoder"
let greeting = username ?? "Anonymous"
print(greeting) // SwiftCoder

The result is always a non-optional value, making it cleaner than if let for simple fallback scenarios.

Try it yourself

func getDisplayName(username: String, defaultName: String) -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals