Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
The exclamation mark (!) is used to force unwrap an optional in Swift, extracting the value inside.
2fill in blank
mediumComplete 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'
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.
✗ Incorrect
In if-let, you unwrap the optional by just using its name without force unwrapping.
3fill in blank
hardFix 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'
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.
✗ Incorrect
Using '??' provides a default value if the optional is nil, avoiding a crash.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!' in filter condition causes syntax error.
Using '.lowercased()' instead of '.uppercased()' changes output.
Using '<' filters wrong names.
✗ Incorrect
We filter names with length greater than 3 and then convert them to uppercase.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' filters wrong names.
Using different variable names inconsistently.
Using force unwrapping inside map.
✗ Incorrect
We filter names longer than 4, then map each name to a tuple of (name, name.count).