0
0
Swiftprogramming~20 mins

Force unwrapping with ! and its danger in Swift - Practice Problems & Coding Challenges

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
1: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!)
AOptional("Alice")
Bnil
CAlice
DRuntime error
Attempts:
2 left
💡 Hint
Force unwrapping extracts the value inside an optional if it is not nil.
Predict Output
intermediate
1:30remaining
What happens when force unwrapping a nil optional?
What will happen when this Swift code runs?
Swift
let age: Int? = nil
print(age!)
ARuntime error: Unexpectedly found nil while unwrapping an Optional value
Bnil
C0
DOptional(nil)
Attempts:
2 left
💡 Hint
Force unwrapping a nil optional causes a crash.
🧠 Conceptual
advanced
2:00remaining
Why is force unwrapping dangerous in Swift?
Which of the following best explains the danger of using force unwrapping (!) in Swift?
AIt slows down the program because it copies the optional value.
BIt always converts optionals to strings, which can cause confusion.
CIt hides compiler errors by automatically unwrapping optionals safely.
DIt can cause the program to crash if the optional is nil at runtime.
Attempts:
2 left
💡 Hint
Think about what happens if the optional has no value.
Predict Output
advanced
1: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")
}
ANo value
Bnil
C0
DRuntime error
Attempts:
2 left
💡 Hint
The if let syntax unwraps only if the optional has a value.
Predict Output
expert
2: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)
ACompile-time error: Cannot force unwrap optional in function parameter
BRuntime error: Unexpectedly found nil while unwrapping an Optional value
CPrints 0
DNo output, function does nothing
Attempts:
2 left
💡 Hint
Force unwrapping nil inside a function causes a runtime crash.