Challenge - 5 Problems
Nil Coalescing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Nil Coalescing with Optional Chaining
What is the output of this Swift code snippet?
Swift
struct User { var name: String? } let user: User? = User(name: nil) let displayName = user?.name ?? "Guest" print(displayName)
Attempts:
2 left
💡 Hint
Remember that optional chaining returns an optional, and nil coalescing provides a default value.
✗ Incorrect
The optional chaining user?.name returns nil because name is nil. The nil coalescing operator then provides "Guest" as the default value.
❓ Predict Output
intermediate2:00remaining
Nested Nil Coalescing Operators
What will be printed by this Swift code?
Swift
let a: Int? = nil let b: Int? = 5 let c: Int? = nil let result = a ?? b ?? c ?? 10 print(result)
Attempts:
2 left
💡 Hint
The nil coalescing operator evaluates from left to right until it finds a non-nil value.
✗ Incorrect
a is nil, so it checks b which is 5 (non-nil), so result is 5.
🔧 Debug
advanced2:30remaining
Unexpected Behavior with Nil Coalescing and Function Calls
Consider this Swift code. What is the output and why?
Swift
func getValue() -> Int? { print("getValue called") return nil } let x: Int? = nil let y = x ?? getValue() ?? 42 print(y)
Attempts:
2 left
💡 Hint
Check when the function getValue() is called in the nil coalescing chain.
✗ Incorrect
Since x is nil, getValue() is called and prints "getValue called". It returns nil, so the final value is 42.
📝 Syntax
advanced1:30remaining
Correct Usage of Nil Coalescing with Optional Binding
Which option correctly uses nil coalescing to assign a non-optional Int from an optional Int?
Attempts:
2 left
💡 Hint
The nil coalescing operator in Swift is ??
✗ Incorrect
Option A uses the correct nil coalescing operator ?? to provide a default value.
🚀 Application
expert2:30remaining
Complex Nil Coalescing in Dictionary Lookup
Given this Swift code, what is the value of finalValue after execution?
Swift
let dict: [String: Int?] = ["a": 1, "b": nil] let finalValue = dict["b"] ?? (10 as Int?) print(finalValue ?? -1)
Attempts:
2 left
💡 Hint
Remember the dictionary value is an optional Int optional, so dict["b"] returns Int??
✗ Incorrect
dict["b"] returns an optional Int? which is .some(nil). The nil coalescing operator unwraps only the outer optional, so finalValue is nil.