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.
Nil coalescing operator deep usage in Swift
optionalValue ?? defaultValue
The operator is written as two question marks: ??.
If optionalValue is not nil, it returns that value; otherwise, it returns defaultValue.
name is nil, displayName becomes "Guest".let name: String? = nil let displayName = name ?? "Guest"
let first: String? = nil let second: String? = "Hello" let message = first ?? second ?? "No greeting"
let number: Int? = nil let result = (number ?? 0) + 10
This program tries to greet the user. It first checks userInput, then defaultGreeting, and finally uses a hardcoded fallback.
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)
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.
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.
Practice
?? do in Swift?Solution
Step 1: Understand the purpose of the nil coalescing operator
The operator??is used to provide a default value when an optional is nil.Step 2: Compare with other options
Options A, C, and D describe different behaviors unrelated to??.Final Answer:
It returns the value of an optional if it is not nil, otherwise returns a default value. -> Option AQuick Check:
Nil coalescing operator = default value fallback [OK]
- Confusing ?? with forced unwrapping (!)
- Thinking ?? converts types
- Assuming ?? compares optionals
Solution
Step 1: Recall the correct syntax for nil coalescing
The correct syntax uses two question marks:??between the optional and the default value.Step 2: Eliminate incorrect options
Options B, C, and D use invalid or incorrect operators.Final Answer:
let value = optionalValue ?? defaultValue -> Option DQuick Check:
Syntax for nil coalescing = ?? [OK]
- Using ?: which is from other languages
- Using single ? instead of ??
- Adding extra question marks ???
let a: Int? = nil let b: Int? = 5 let c: Int? = nil let result = a ?? b ?? c ?? 10 print(result)
Solution
Step 1: Evaluate the chained nil coalescing
The expressiona ?? b ?? c ?? 10checks each optional from left to right and returns the first non-nil value.Step 2: Check each optional's value
ais nil, so move tobwhich is 5 (non-nil), so the result is 5.Final Answer:
5 -> Option AQuick Check:
First non-nil value = 5 [OK]
- Assuming nil is returned if first is nil
- Ignoring chaining order
- Thinking default 10 is always returned
let x: Int? = nil let y: Int = 3 let z = x ?? y ?? 5 print(z)
Solution
Step 1: Understand the types involved in nil coalescing
The operator??requires the right side to be the same type as the optional or a non-optional fallback value.Step 2: Analyze the expression
Here,x ?? y ?? 5xisInt?,yisInt, buty ?? 5is invalid becauseyis not optional, so you cannot use??on it.Final Answer:
Cannot use ?? with non-optional y -> Cannot use ?? with non-optional yQuick Check:
Right side of ?? must be optional or value [OK]
- Using ?? on non-optional values
- Confusing optional and non-optional types
- Assuming ?? works like || operator
finalValue?func getValue() -> Int? { return nil }
let a: Int? = nil
let b: Int? = getValue()
let c: Int? = 7
let finalValue = a ?? b ?? c ?? 0Solution
Step 1: Evaluate each optional in the chain
ais nil,bis nil (from getValue()),cis 7 (non-nil).Step 2: Apply nil coalescing operator
The expressiona ?? b ?? c ?? 0returns the first non-nil value, which is 7.Final Answer:
7 -> Option CQuick Check:
First non-nil in chain = 7 [OK]
- Assuming function return nil means error
- Ignoring that c is non-nil
- Thinking default 0 is returned always
Ready to prove it?
Pass the test and this pattern moves unknown
