0
0
Swiftprogramming~20 mins

Nil coalescing operator (??) in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nil Coalescing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
ACompilation error
Bnil
C0
D10
Attempts:
2 left
💡 Hint
Remember, the nil coalescing operator returns the left value if it is not nil, otherwise the right value.
Predict Output
intermediate
2: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)
AAlice
Bnil
CGuest
DCompilation error
Attempts:
2 left
💡 Hint
If the optional has a value, the nil coalescing operator returns that value.
Predict Output
advanced
2: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)
ACompilation error
Bnil
C5
D10
Attempts:
2 left
💡 Hint
The nil coalescing operator can be chained to check multiple optionals.
Predict Output
advanced
2: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)
Anil
BCompilation error
Cdefault
DOptional("")
Attempts:
2 left
💡 Hint
The nil coalescing operator requires both sides to have the same type.
🧠 Conceptual
expert
3: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
A42
Bnil
CCompilation error
DOptional(42)
Attempts:
2 left
💡 Hint
The function returns nil, so the nil coalescing operator uses the default value.