Challenge - 5 Problems
Swift Optional Safety Master
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 optionals?
Consider this Swift code snippet that uses optionals. What will it print?
Swift
var name: String? = "Alice" if let unwrappedName = name { print("Hello, \(unwrappedName)!") } else { print("No name provided.") }
Attempts:
2 left
💡 Hint
Look at how 'if let' unwraps the optional safely.
✗ Incorrect
The 'if let' syntax unwraps the optional 'name' safely. Since 'name' contains "Alice", it prints the greeting with the unwrapped value.
🧠 Conceptual
intermediate1:30remaining
Why does Swift use optionals instead of null pointers?
Why are optionals considered safer than traditional null pointers in Swift?
Attempts:
2 left
💡 Hint
Think about how optionals require you to check for a value before use.
✗ Incorrect
Optionals require explicit handling of missing values, which helps avoid unexpected nil crashes common with null pointers.
🔧 Debug
advanced1:30remaining
What error does this Swift code raise?
This Swift code tries to force unwrap an optional. What error will it cause at runtime?
Swift
var age: Int? = nil print(age!)
Attempts:
2 left
💡 Hint
What happens if you force unwrap a nil optional?
✗ Incorrect
Force unwrapping a nil optional causes a runtime crash with the message about unexpectedly finding nil.
📝 Syntax
advanced1:00remaining
Which option correctly declares an optional integer in Swift?
Choose the correct syntax to declare an optional integer variable named 'score'.
Attempts:
2 left
💡 Hint
Remember the '?' symbol is used to declare optionals.
✗ Incorrect
The correct syntax uses '?' after the type name to declare an optional variable.
🚀 Application
expert2:00remaining
How many items are in the resulting array after filtering non-nil values?
Given this Swift code, how many elements does 'validScores' contain?
Swift
let scores: [Int?] = [10, nil, 20, nil, 30] let validScores = scores.compactMap { $0 }
Attempts:
2 left
💡 Hint
compactMap removes nil values and unwraps optionals.
✗ Incorrect
compactMap filters out nils and unwraps optionals, so only 10, 20, and 30 remain, totaling 3 elements.