0
0
Swiftprogramming~20 mins

Nil represents absence of value in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nil Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code using nil?
Consider this Swift code snippet. What will it print?
Swift
var name: String? = nil
if name == nil {
    print("No name provided")
} else {
    print("Name is \(name!)")
}
ACompilation error
BName is nil
CName is Optional(nil)
DNo name provided
Attempts:
2 left
💡 Hint
Think about what happens when you compare an optional variable to nil.
Predict Output
intermediate
2:00remaining
What happens when you force unwrap a nil optional?
What will happen when this Swift code runs?
Swift
var number: Int? = nil
print(number!)
ARuntime crash due to force unwrapping nil
BPrints nil
CPrints 0
DCompilation error
Attempts:
2 left
💡 Hint
Force unwrapping nil causes a runtime error.
🧠 Conceptual
advanced
2:00remaining
Which statement about nil in Swift is true?
Choose the correct statement about nil in Swift.
Anil is the same as an empty string for String variables
Bnil can be assigned to any variable type
Cnil represents the absence of a value only for optional types
Dnil can be used to reset non-optional variables
Attempts:
2 left
💡 Hint
Think about which types can hold nil values.
Predict Output
advanced
2:00remaining
What is the output of this optional binding code?
What will this Swift code print?
Swift
var age: Int? = nil
if let actualAge = age {
    print("Age is \(actualAge)")
} else {
    print("Age is not set")
}
ACompilation error
BAge is not set
CAge is nil
DAge is 0
Attempts:
2 left
💡 Hint
Optional binding only runs the if block if the optional has a value.
Predict Output
expert
2:00remaining
What is the output of this Swift code with nil coalescing?
What will this Swift code print?
Swift
var city: String? = nil
let displayCity = city ?? "Unknown"
print(displayCity)
AUnknown
Bnil
CCompilation error
DOptional(nil)
Attempts:
2 left
💡 Hint
The nil coalescing operator provides a default value if the optional is nil.