Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare an optional integer variable.
Swift
var number: Int[1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!' instead of '?' to declare an optional.
Forgetting to add any symbol after the type.
✗ Incorrect
In Swift, adding a ? after a type declares it as optional, meaning it can hold a value or be nil.
2fill in blank
mediumComplete the code to safely unwrap an optional using if-let.
Swift
if let safeNumber = optionalNumber[1] { print(safeNumber) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '=' in if-let.
Using '!' or '?' in this context.
✗ Incorrect
The if let syntax uses = to assign the unwrapped value if it exists.
3fill in blank
hardFix the error in force unwrapping an optional.
Swift
let forcedValue = optionalValue[1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '?' instead of '!' for force unwrapping.
Using '=' or ':' which are invalid here.
✗ Incorrect
Force unwrapping uses ! to get the value inside an optional, but it can crash if nil.
4fill in blank
hardFill both blanks to create a dictionary comprehension filtering non-nil values.
Swift
let filtered = dictionary.compactMapValues { $0[1] } .filter { $0[2] nil } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!' in optional chaining which can cause crashes.
Using '==' instead of '!=' to filter nil.
✗ Incorrect
Use ? to safely unwrap in compactMapValues and != to filter out nil values.
5fill in blank
hardFill all three blanks to unwrap an optional with guard and provide a default value.
Swift
guard let value = optionalValue[1] else { return [2] } let finalValue = value[3]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not using guard let syntax correctly.
Returning nil instead of a default value.
Forgetting to unwrap after guard.
✗ Incorrect
Use ? for optional chaining, 0 as default return, and ! to force unwrap after guard.