0
0
Swiftprogramming~10 mins

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

Choose your learning style9 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.