Challenge - 5 Problems
Nil Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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!)") }
Attempts:
2 left
💡 Hint
Think about what happens when you compare an optional variable to nil.
✗ Incorrect
The variable 'name' is an optional String set to nil. The if condition checks if name is nil, which is true, so it prints 'No name provided'.
❓ Predict Output
intermediate2: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!)
Attempts:
2 left
💡 Hint
Force unwrapping nil causes a runtime error.
✗ Incorrect
Trying to force unwrap an optional that is nil causes a runtime crash with a fatal error.
🧠 Conceptual
advanced2:00remaining
Which statement about nil in Swift is true?
Choose the correct statement about nil in Swift.
Attempts:
2 left
💡 Hint
Think about which types can hold nil values.
✗ Incorrect
In Swift, only optional types can hold nil to represent absence of a value. Non-optional types cannot be nil.
❓ Predict Output
advanced2: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") }
Attempts:
2 left
💡 Hint
Optional binding only runs the if block if the optional has a value.
✗ Incorrect
Since age is nil, the else block runs and prints 'Age is not set'.
❓ Predict Output
expert2: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)
Attempts:
2 left
💡 Hint
The nil coalescing operator provides a default value if the optional is nil.
✗ Incorrect
Since city is nil, the nil coalescing operator returns the default string 'Unknown'.