0
0
Swiftprogramming~10 mins

Why optionals are Swift's core safety feature - Test Your Understanding

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

Complete the code to declare an optional integer variable.

Swift
var number: Int[1]
Drag options to blanks, or click blank then click option'
A?
B!
C=
D:
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!' instead of '?' to declare an optional.
Forgetting to add any symbol after the type.
2fill in blank
medium

Complete 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'
A!
B?
C=
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '=' in if-let.
Using '!' or '?' in this context.
3fill in blank
hard

Fix the error in force unwrapping an optional.

Swift
let forcedValue = optionalValue[1]
Drag options to blanks, or click blank then click option'
A?
B:
C=
D!
Attempts:
3 left
💡 Hint
Common Mistakes
Using '?' instead of '!' for force unwrapping.
Using '=' or ':' which are invalid here.
4fill in blank
hard

Fill 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'
A!
B==
C!=
D?
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!' in optional chaining which can cause crashes.
Using '==' instead of '!=' to filter nil.
5fill in blank
hard

Fill 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'
A?
B0
D!
Attempts:
3 left
💡 Hint
Common Mistakes
Not using guard let syntax correctly.
Returning nil instead of a default value.
Forgetting to unwrap after guard.