What does the nil coalescing operator (??) do in Swift?
It provides a default value when an optional is nil. If the optional has a value, it unwraps and returns it; otherwise, it returns the default value.
Click to reveal answer
beginner
How would you use the nil coalescing operator to assign a default name if a variable 'username' is nil?
You write: let name = username ?? "Guest". This means if 'username' is nil, 'name' will be "Guest".
Click to reveal answer
beginner
True or False: The nil coalescing operator (??) can only be used with optional values.
True. It is designed to work with optionals to provide a fallback value when the optional is nil.
Click to reveal answer
beginner
What is the result of this Swift code? <br><pre>let a: Int? = nil<br>let b = a ?? 10</pre>
The value of 'b' will be 10 because 'a' is nil, so the nil coalescing operator returns the default value 10.
Click to reveal answer
intermediate
Explain why nil coalescing operator (??) is useful in real-life programming.
It helps avoid crashes by safely unwrapping optionals and providing a fallback value, making code simpler and safer when dealing with missing data.
Click to reveal answer
What does the nil coalescing operator (??) return if the optional on the left is not nil?
AThe unwrapped value of the optional
BThe default value on the right
Cnil
DAn error
✗ Incorrect
If the optional has a value, the operator returns that value instead of the default.
Which of these is a correct use of the nil coalescing operator?
Alet result = optionalValue ?? 5
Blet result = 5 ?? optionalValue
Clet result = optionalValue ? 5
Dlet result = optionalValue || 5
✗ Incorrect
The operator is used as 'optional ?? defaultValue'.
If you have 'let x: String? = nil', what is the value of 'let y = x ?? "Hello"'?
A"Hello"
Bnil
Cx
DAn error
✗ Incorrect
Since x is nil, y gets the default string "Hello".
Can the nil coalescing operator be chained like 'a ?? b ?? c'?
AYes, it returns the first non-nil value
BNo, it causes a syntax error
COnly if all are integers
DOnly if all are strings
✗ Incorrect
You can chain it to check multiple optionals and get the first non-nil value.
What type must the right side of the nil coalescing operator have?
AThe same type as the unwrapped optional
BAny type
COnly optional types
DOnly String type
✗ Incorrect
The default value must match the type of the optional's unwrapped value.
Describe how the nil coalescing operator (??) works in Swift and give a simple example.
Think about how to handle missing values safely.
You got /3 concepts.
Why is using the nil coalescing operator better than force unwrapping optionals?
Consider what happens if the optional is nil.
You got /4 concepts.
Practice
(1/5)
1. What does the nil coalescing operator ?? do in Swift?
easy
A. It unwraps an optional without checking for nil.
B. It provides a default value if an optional is nil.
C. It converts a non-optional to an optional.
D. It forces a runtime error if the optional is nil.
Solution
Step 1: Understand optional values
Optionals may contain a value or nil (no value).
Step 2: Role of nil coalescing operator
The operator ?? returns the optional's value if it exists; otherwise, it returns the default value provided.
Final Answer:
It provides a default value if an optional is nil. -> Option B
Quick Check:
Nil coalescing = default value if nil [OK]
Hint: Remember: ?? means "use this if nil" [OK]
Common Mistakes:
Thinking ?? unwraps without nil check
Confusing ?? with forced unwrapping (!)
Assuming ?? converts types
2. Which of the following is the correct syntax to use the nil coalescing operator in Swift?
easy
A. let value = optionalValue !! defaultValue
B. let value = optionalValue ?: defaultValue
C. let value = optionalValue ? defaultValue
D. let value = optionalValue ?? defaultValue
Solution
Step 1: Recall the syntax of nil coalescing
The nil coalescing operator is written as ?? between an optional and a default value.
Step 2: Match correct syntax
let value = optionalValue ?? defaultValue uses ?? correctly: let value = optionalValue ?? defaultValue.
Final Answer:
let value = optionalValue ?? defaultValue -> Option D
Quick Check:
Correct syntax uses ?? [OK]
Hint: Look for double question marks ?? in syntax [OK]
Common Mistakes:
Using ?: which is from other languages
Using single ? without ??
Using !! which is invalid
3. What will be the output of the following Swift code?
var name: String? = nil
let displayName = name ?? "Guest"
print(displayName)
medium
A. Guest
B. Optional("Guest")
C. nil
D. Error: Cannot print optional
Solution
Step 1: Check the optional value
The variable name is nil.
Step 2: Apply nil coalescing operator
The expression name ?? "Guest" returns "Guest" because name is nil.
Final Answer:
Guest -> Option A
Quick Check:
nil ?? "Guest" = "Guest" [OK]
Hint: If optional is nil, ?? returns the default value [OK]
Common Mistakes:
Expecting nil to print
Thinking print shows Optional(...)
Confusing ?? with forced unwrap
4. Identify the error in this Swift code snippet using the nil coalescing operator:
let age: Int? = 25
let userAge = age ??
print(userAge)
medium
A. Optional variable cannot be used with ??
B. print statement syntax is incorrect
C. Missing default value after ?? operator
D. age should not be optional
Solution
Step 1: Check nil coalescing usage
The operator ?? must be followed by a default value to use if the optional is nil.
Step 2: Identify missing default value
In the code, age ?? is incomplete because no default value is provided after ??.
Final Answer:
Missing default value after ?? operator -> Option C
Quick Check:
?? needs a value after it [OK]
Hint: Always provide a value after ?? [OK]
Common Mistakes:
Leaving ?? without default value
Thinking optional can't be used with ??
Misplacing print statement
5. Given the dictionary let scores: [String: Int?] = ["Alice": 85, "Bob": nil], which expression correctly uses the nil coalescing operator to get Bob's score or 0 if nil?
hard
A. let bobScore = scores["Bob"] ?? nil ?? 0
B. let bobScore = scores["Bob"]! ?? 0
C. let bobScore = scores["Bob"] ?? Optional(0)
D. let bobScore = scores["Bob"] ?? 0
Solution
Step 1: Understand dictionary value type
The dictionary stores optional Int values: Int? inside the dictionary optional lookup, so scores["Bob"] returns Int??.
Step 2: Use nil coalescing correctly
Chaining scores["Bob"] ?? nil ?? 0 first flattens the double optional to Int? (returns inner value or nil), then applies ?? 0 to provide 0 if nil, yielding Int. For "Bob", some(nil) ?? nil = nil, then nil ?? 0 = 0.
Final Answer:
let bobScore = scores["Bob"] ?? nil ?? 0 -> Option A
Quick Check:
?? nil ?? 0 handles [Key: Opt<V>] [OK]
Hint: Chain ?? nil ?? 0 for dict of optionals [OK]
Common Mistakes:
Forcing unwrap before ?? causing crash
Direct ?? 0 causes type mismatch
Optional(0) doesn't handle inner nil
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.