0
0
Swiftprogramming~20 mins

Nil coalescing operator deep usage 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
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)
Anil
B"Guest"
C"Optional(nil)"
DCompilation error
Attempts:
2 left
💡 Hint
Remember that optional chaining returns an optional, and nil coalescing provides a default value.
Predict Output
intermediate
2: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)
A5
Bnil
C10
DCompilation error
Attempts:
2 left
💡 Hint
The nil coalescing operator evaluates from left to right until it finds a non-nil value.
🔧 Debug
advanced
2: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)
AgetValue called\nnil
B42
CgetValue called\n42
DCompilation error
Attempts:
2 left
💡 Hint
Check when the function getValue() is called in the nil coalescing chain.
📝 Syntax
advanced
1: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?
Alet value = optionalInt ?? 0
Blet value = optionalInt ? 0
Clet value = optionalInt || 0
Dlet value = optionalInt ?: 0
Attempts:
2 left
💡 Hint
The nil coalescing operator in Swift is ??
🚀 Application
expert
2: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)
A-1
B10
C1
Dnil
Attempts:
2 left
💡 Hint
Remember the dictionary value is an optional Int optional, so dict["b"] returns Int??