Challenge - 5 Problems
Nil Coalescing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nil coalescing with optional Int
What is the output of this Swift code snippet?
Swift
let a: Int? = nil let b = a ?? 10 print(b)
Attempts:
2 left
💡 Hint
Remember, the nil coalescing operator returns the left value if it is not nil, otherwise the right value.
✗ Incorrect
Since 'a' is nil, the expression 'a ?? 10' returns 10. So, the printed output is 10.
❓ Predict Output
intermediate2:00remaining
Nil coalescing with non-nil optional
What will be printed by this Swift code?
Swift
let name: String? = "Alice" let displayName = name ?? "Guest" print(displayName)
Attempts:
2 left
💡 Hint
If the optional has a value, the nil coalescing operator returns that value.
✗ Incorrect
The optional 'name' contains "Alice", so 'name ?? "Guest"' evaluates to "Alice".
❓ Predict Output
advanced2:00remaining
Chained nil coalescing operator output
What is the output of this Swift code?
Swift
let x: Int? = nil let y: Int? = 5 let z = x ?? y ?? 10 print(z)
Attempts:
2 left
💡 Hint
The nil coalescing operator can be chained to check multiple optionals.
✗ Incorrect
Since 'x' is nil, it checks 'y' which is 5, so 'z' becomes 5.
❓ Predict Output
advanced2:00remaining
Nil coalescing with different types
What error or output occurs when running this Swift code?
Swift
let a: Int? = nil let b = a ?? "default" print(b)
Attempts:
2 left
💡 Hint
The nil coalescing operator requires both sides to have the same type.
✗ Incorrect
The left side is Int? and the right side is String, so the compiler reports a type mismatch error.
🧠 Conceptual
expert3:00remaining
Behavior of nil coalescing with function returning optional
Consider the following Swift code. What is the value of 'result' after execution?
Swift
func fetchValue() -> Int? { return nil } let result = fetchValue() ?? 42
Attempts:
2 left
💡 Hint
The function returns nil, so the nil coalescing operator uses the default value.
✗ Incorrect
Since fetchValue() returns nil, 'result' is assigned the default value 42.