Challenge - 5 Problems
Swift Optional Safety Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
What is the output of force unwrapping a non-nil optional?
Consider the following Swift code. What will be printed when it runs?
Swift
let name: String? = "Alice" print(name!)
Attempts:
2 left
💡 Hint
Force unwrapping extracts the value inside an optional if it is not nil.
✗ Incorrect
The optional 'name' contains the string "Alice". Using '!' unwraps it safely here, so it prints "Alice".
❓ Predict Output
intermediate1:30remaining
What happens when force unwrapping a nil optional?
What will happen when this Swift code runs?
Swift
let age: Int? = nil print(age!)
Attempts:
2 left
💡 Hint
Force unwrapping a nil optional causes a crash.
✗ Incorrect
Trying to unwrap 'age' which is nil causes a runtime crash with the error message shown.
🧠 Conceptual
advanced2:00remaining
Why is force unwrapping dangerous in Swift?
Which of the following best explains the danger of using force unwrapping (!) in Swift?
Attempts:
2 left
💡 Hint
Think about what happens if the optional has no value.
✗ Incorrect
Force unwrapping an optional that is nil causes a runtime crash, making it unsafe unless you are sure the value exists.
❓ Predict Output
advanced1:30remaining
What is the output of this code with conditional unwrapping?
What will this Swift code print?
Swift
let number: Int? = nil if let unwrapped = number { print(unwrapped) } else { print("No value") }
Attempts:
2 left
💡 Hint
The if let syntax unwraps only if the optional has a value.
✗ Incorrect
Since 'number' is nil, the else block runs and prints "No value" safely without crashing.
❓ Predict Output
expert2:00remaining
What error does this code produce when force unwrapping a nil optional inside a function?
Consider this Swift function and call. What error will occur?
Swift
func printLength(of text: String?) { print(text!.count) } printLength(of: nil)
Attempts:
2 left
💡 Hint
Force unwrapping nil inside a function causes a runtime crash.
✗ Incorrect
The function tries to unwrap 'text' which is nil, causing a runtime crash with the error message shown.