0
0
Swiftprogramming~5 mins

Nil coalescing operator (??) 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).

When you want to use a value that might be missing, but have a backup value ready.
When reading user input that could be empty or nil, and you want a safe default.
When working with optional variables and you want to avoid writing long if-else checks.
When you want to simplify your code by handling nil values in one line.
Syntax
Swift
optionalValue ?? defaultValue

The operator checks if optionalValue is nil.

If it is nil, it uses defaultValue instead.

Examples
If name is nil, displayName becomes "Guest".
Swift
let name: String? = nil
let displayName = name ?? "Guest"
If score has a value, finalScore uses it; otherwise, it uses 0.
Swift
let score: Int? = 85
let finalScore = score ?? 0
Since input is not nil, message will be "Hello".
Swift
var input: String? = "Hello"
let message = input ?? "No message"
Sample Program

This program shows how the nil coalescing operator returns a default when the optional is nil, and the actual value when it is not.

Swift
var userInput: String? = nil
let result = userInput ?? "Default value"
print(result)

userInput = "Swift is fun!"
let newResult = userInput ?? "Default value"
print(newResult)
OutputSuccess
Important Notes

The nil coalescing operator only works with optionals.

You can chain multiple nil coalescing operators for multiple fallback values.

Summary

The nil coalescing operator (??) provides a simple way to use a default value when an optional is nil.

It helps keep your code clean and safe from unexpected nil values.