0
0
Swiftprogramming~20 mins

Why optionals are Swift's core safety feature - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Optional Safety Master
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 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.")
}
ANo name provided.
BHello, Alice!
COptional("Alice")
Dnil
Attempts:
2 left
💡 Hint
Look at how 'if let' unwraps the optional safely.
🧠 Conceptual
intermediate
1:30remaining
Why does Swift use optionals instead of null pointers?
Why are optionals considered safer than traditional null pointers in Swift?
ABecause optionals force you to handle the absence of a value explicitly, preventing runtime crashes.
BBecause optionals allow any type to be converted to a string automatically.
CBecause optionals automatically initialize variables with default values.
DBecause optionals make all variables immutable by default.
Attempts:
2 left
💡 Hint
Think about how optionals require you to check for a value before use.
🔧 Debug
advanced
1: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!)
APrints 'nil' without error
BCompile-time error: Cannot force unwrap a nil optional
CRuntime error: Unexpectedly found nil while unwrapping an Optional value
DPrints '0' as default integer value
Attempts:
2 left
💡 Hint
What happens if you force unwrap a nil optional?
📝 Syntax
advanced
1:00remaining
Which option correctly declares an optional integer in Swift?
Choose the correct syntax to declare an optional integer variable named 'score'.
Avar score: Int!
Bvar score: Optional Int
Cvar score = Optional<Int>
Dvar score: Int?
Attempts:
2 left
💡 Hint
Remember the '?' symbol is used to declare optionals.
🚀 Application
expert
2: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 }
A3
B5
C2
D0
Attempts:
2 left
💡 Hint
compactMap removes nil values and unwraps optionals.