Bird
Raised Fist0
Swiftprogramming~10 mins

Force unwrapping with ! and its danger in Swift - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to force unwrap the optional value.

Swift
let name: String? = "Alice"
let unwrappedName = name[1]
Drag options to blanks, or click blank then click option'
A?
B!
C.
D:
Attempts:
3 left
💡 Hint
Common Mistakes
Using '?' instead of '!' which only safely unwraps.
Using '.' which accesses properties or methods.
Using ':' which is not related to unwrapping.
2fill in blank
medium

Complete the code to safely unwrap the optional using if-let instead of force unwrapping.

Swift
let age: Int? = 30
if let unwrappedAge = [1] {
    print("Age is \(unwrappedAge)")
}
Drag options to blanks, or click blank then click option'
Aage
Bage!
Cage?
Dage ?? 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'age!' inside if-let which causes a crash if nil.
Using 'age?' which is not valid syntax here.
Using 'age ?? 0' which provides a default but is not unwrapping.
3fill in blank
hard

Fix the error by replacing force unwrapping with safe unwrapping.

Swift
let city: String? = nil
print("City is \(city[1])")
Drag options to blanks, or click blank then click option'
A!
B? ?? "Unknown"
C?
D?? "Unknown"
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!' causes a runtime crash if city is nil.
Using '?' alone does not provide a default value.
Using '? ??' is invalid syntax.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that includes only names with length greater than 3.

Swift
let names = ["Tom", "Anna", "Bob", "Catherine"]
let filteredNames = names.filter { $0 [1] 3 }.map { $0[2] }
Drag options to blanks, or click blank then click option'
A>
B!
C.uppercased()
D.lowercased()
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!' in filter condition causes syntax error.
Using '.lowercased()' instead of '.uppercased()' changes output.
Using '<' filters wrong names.
5fill in blank
hard

Fill all three blanks to create a dictionary of names and their lengths, including only names longer than 4 characters.

Swift
let names = ["John", "Elizabeth", "Mark", "Samantha"]
let nameLengths = Dictionary(uniqueKeysWithValues: names.filter { $0.count [1] 4 }.map { ([2], [3]) in ([2], [3].count) })
Drag options to blanks, or click blank then click option'
A>
Bname
Cword
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' filters wrong names.
Using different variable names inconsistently.
Using force unwrapping inside map.

Practice

(1/5)
1. What does force unwrapping an optional with ! do in Swift?
easy
A. It extracts the value inside the optional if it is not nil.
B. It safely checks if the optional is nil before using it.
C. It converts the optional to a string automatically.
D. It creates a new optional with the same value.

Solution

  1. Step 1: Understand what an optional is

    An optional may contain a value or nil, representing absence of value.
  2. Step 2: Understand force unwrapping

    Using ! extracts the value inside the optional if it exists, otherwise it crashes.
  3. Final Answer:

    It extracts the value inside the optional if it is not nil. -> Option A
  4. Quick Check:

    Force unwrapping = extract value [OK]
Hint: Force unwrap pulls value out but crashes if nil [OK]
Common Mistakes:
  • Thinking force unwrap safely checks nil
  • Confusing force unwrap with optional binding
  • Assuming force unwrap converts types automatically
2. Which of the following is the correct syntax to force unwrap an optional integer named number?
easy
A. let value = !number
B. let value = number?
C. let value = number!
D. let value = number.unwrap()

Solution

  1. Step 1: Recall force unwrap syntax

    Force unwrapping uses the ! after the optional variable name.
  2. Step 2: Check each option

    let value = number! uses number! which is correct syntax; others are invalid or incorrect.
  3. Final Answer:

    let value = number! -> Option C
  4. Quick Check:

    Force unwrap syntax = variable! [OK]
Hint: Force unwrap uses exclamation after variable [OK]
Common Mistakes:
  • Placing ! before the variable
  • Using ? instead of ! for force unwrap
  • Calling a non-existent unwrap() method
3. What will be the output of this Swift code?
var name: String? = "Alice"
print(name!)
medium
A. Alice
B. Runtime crash
C. Optional("Alice")
D. nil

Solution

  1. Step 1: Check the optional value

    The optional name contains the string "Alice", not nil.
  2. Step 2: Force unwrap and print

    Force unwrapping name! extracts "Alice" and prints it directly.
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    Force unwrap non-nil optional prints value [OK]
Hint: Force unwrap prints value if not nil [OK]
Common Mistakes:
  • Expecting Optional(...) printed
  • Thinking it prints nil
  • Assuming it crashes even if value exists
4. Consider this code snippet:
var age: Int? = nil
print(age!)

What is the problem and how to fix it?
medium
A. No problem; prints nil safely.
B. Syntax error; fix by removing !.
C. Prints 0; fix by initializing age to 0.
D. Runtime crash due to force unwrapping nil; fix by optional binding.

Solution

  1. Step 1: Identify the cause of crash

    Force unwrapping age! when age is nil causes a runtime crash.
  2. Step 2: Fix using optional binding

    Use if let or guard let to safely unwrap before printing.
  3. Final Answer:

    Runtime crash due to force unwrapping nil; fix by optional binding. -> Option D
  4. Quick Check:

    Force unwrap nil = crash; use safe unwrap [OK]
Hint: Never force unwrap nil; use if let or guard let [OK]
Common Mistakes:
  • Assuming force unwrap prints nil safely
  • Removing ! without handling optional
  • Initializing to 0 without reason
5. You have an optional string var input: String? = nil. You want to print its value only if it exists, otherwise print "No input". Which code safely achieves this without crashing?
hard
A. print(input!)
B. print(input ?? "No input")
C. print(input!) ?? "No input"
D. print(input != nil ? input! : nil)

Solution

  1. Step 1: Understand the goal

    Print the value if it exists; otherwise print "No input" safely without crash.
  2. Step 2: Analyze options

    print(input ?? "No input") uses nil-coalescing operator ?? to provide default string if input is nil, avoiding force unwrap crash.
  3. Final Answer:

    print(input ?? "No input") -> Option B
  4. Quick Check:

    Use ?? to safely unwrap or default [OK]
Hint: Use ?? to provide default instead of force unwrap [OK]
Common Mistakes:
  • Force unwrapping nil causing crash
  • Misusing ?? with force unwrap
  • Printing nil instead of default string
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard