0
0
Swiftprogramming~7 mins

Nil coalescing operator deep usage in Swift

Choose your learning style9 modes available
Introduction

The nil coalescing operator helps you provide a default value when something might be missing (nil). It makes your code safer and easier to read.

When you want to use a default value if an optional variable is nil.
When you chain multiple optional values and want the first non-nil one.
When you want to simplify code that checks for nil before using a value.
When you want to avoid writing long if-let or guard statements for optionals.
Syntax
Swift
optionalValue ?? defaultValue

The operator is written as two question marks: ??.

If optionalValue is not nil, it returns that value; otherwise, it returns defaultValue.

Examples
If name is nil, displayName becomes "Guest".
Swift
let name: String? = nil
let displayName = name ?? "Guest"
Chains multiple optionals, picking the first non-nil value.
Swift
let first: String? = nil
let second: String? = "Hello"
let message = first ?? second ?? "No greeting"
Uses nil coalescing to provide a default number before adding.
Swift
let number: Int? = nil
let result = (number ?? 0) + 10
Sample Program

This program tries to greet the user. It first checks userInput, then defaultGreeting, and finally uses a hardcoded fallback.

Swift
import Foundation

// Optional user input
let userInput: String? = nil

// Optional default greeting
let defaultGreeting: String? = "Hello, friend!"

// Use nil coalescing to pick the first non-nil greeting
let greeting = userInput ?? defaultGreeting ?? "Hi there!"

print(greeting)
OutputSuccess
Important Notes

You can chain multiple nil coalescing operators to check several optionals in order.

The right side of ?? is only evaluated if the left side is nil, which can save work.

Use parentheses if you combine nil coalescing with other operators to keep code clear.

Summary

The nil coalescing operator ?? provides a simple way to use default values for optionals.

It helps avoid long if-let or guard statements by making code shorter and clearer.

You can chain multiple ?? operators to pick the first non-nil value from many optionals.