Understanding the Nil Coalescing Operator in Swift

Learn how Swift's nil coalescing operator returns a default value when an optional is nil.
Written by

Joash Tubaga

Updated on

Apr 06 2026

Table of contents

    Overview

    The nil coalescing operator, written as ??, is a concise way to handle optional values in Swift. It checks whether an optional contains a value. If it does, Swift uses that value. If the optional is nil, Swift uses a fallback value instead.

    This is useful anywhere an optional might not contain data: user input, saved settings, parsed JSON, API responses, or values you want to display in the UI.

    Basic Syntax

    The left side is an optional. The right side is the default value Swift should use when the optional is nil.

    let value = optionalValue ?? fallbackValue

    Both sides must produce the same kind of value. For example, if the optional is a String?, the fallback should be a String.

    A Simple Example

    Here is the original example from the article, updated into the newer code block style:

    var optionalName: String? = nil
    let defaultName = "Guest"
    
    let nameToDisplay = optionalName ?? defaultName
    print(nameToDisplay) // Output: Guest

    Because optionalName is nil, Swift uses defaultName. The result is the string "Guest".

    When the Optional Has a Value

    If the optional contains a value, Swift uses the value on the left side and ignores the fallback.

    var optionalName: String? = "Chris"
    let defaultName = "Guest"
    
    let nameToDisplay = optionalName ?? defaultName
    print(nameToDisplay) // Output: Chris

    This is the key behavior: ?? only uses the fallback when the optional is actually nil.

    The Longhand Version

    The nil coalescing operator is shorthand for a common optional-checking pattern. This longer version works the same way:

    let nameToDisplay: String
    
    if let optionalName {
        nameToDisplay = optionalName
    } else {
        nameToDisplay = "Guest"
    }

    The operator keeps simple fallback logic readable without needing an if let block every time.

    Using It with App Settings

    A common use case is showing a stored setting when it exists, or a default value when it does not.

    let savedUsername: String? = nil
    let username = savedUsername ?? "New User"
    
    print("Welcome, \(username)!")

    This lets the app display something friendly even before the user has provided a name.

    Using It with Dictionaries

    Dictionary lookups return optionals because the key might not exist. Nil coalescing is a clean way to provide a default.

    let scores = [
        "Maya": 92,
        "Chris": 88
    ]
    
    let alexScore = scores["Alex"] ?? 0
    print(alexScore)

    Since the dictionary does not have an "Alex" key, alexScore becomes 0.

    Chaining Fallbacks

    You can chain nil coalescing operators when you have more than one optional source.

    let nickname: String? = nil
    let fullName: String? = "Taylor Lee"
    
    let displayName = nickname ?? fullName ?? "Guest"
    print(displayName)

    Swift checks each value from left to right and uses the first non-nil result. If both optionals are nil, it uses "Guest".

    Common Mistakes

    Using a fallback with the wrong type

    If the optional is a String?, the fallback needs to be a String, not an Int or another unrelated type.

    Using nil coalescing for complex logic

    The ?? operator is best for simple fallback values. If the fallback needs several steps or side effects, an if statement or helper function is usually clearer.

    Forgetting that dictionary values are optional

    Even if a dictionary stores non-optional values, reading a value by key returns an optional because the key may be missing.

    Quick Reference

    ExpressionResult
    optionalName ?? "Guest"Uses optionalName if it has a value, otherwise "Guest"
    scores["Alex"] ?? 0Uses a dictionary value if the key exists, otherwise 0
    nickname ?? fullName ?? "Guest"Checks multiple optional values from left to right
    String?An optional string that can contain a string or nil

    Summary

    • The nil coalescing operator is written as ??.
    • It returns the optional's value when the optional is not nil.
    • It returns a fallback value when the optional is nil.
    • The optional value and fallback value need compatible types.
    • It is especially useful for UI text, settings, dictionary lookups, and parsed data.

    Nil coalescing is small, but it does a lot for readability. It gives your code a clear fallback path while keeping common optional-handling code short and predictable.