0
0
Swiftprogramming~10 mins

CompactMap for optional unwrapping in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - CompactMap for optional unwrapping
Start with array of optionals
Apply compactMap
Check each element
Not nil
Keep value
Return array without nils
compactMap takes an array with optional values, removes all nils, and returns an array of only the unwrapped values.
Execution Sample
Swift
let numbers: [Int?] = [1, nil, 3, nil, 5]
let unwrapped = numbers.compactMap { $0 }
print(unwrapped)
This code removes nil values from the array and prints only the non-nil numbers.
Execution Table
StepElementIs nil?ActionResulting Array
11NoKeep 1[1]
2nilYesDiscard nil[1]
33NoKeep 3[1, 3]
4nilYesDiscard nil[1, 3]
55NoKeep 5[1, 3, 5]
End--All elements processed[1, 3, 5]
💡 All elements checked; nil values removed; final array contains only unwrapped Ints.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
numbers[1, nil, 3, nil, 5][1, nil, 3, nil, 5][1, nil, 3, nil, 5][1, nil, 3, nil, 5][1, nil, 3, nil, 5][1, nil, 3, nil, 5][1, nil, 3, nil, 5]
unwrapped[][1][1][1, 3][1, 3][1, 3, 5][1, 3, 5]
Key Moments - 2 Insights
Why does compactMap remove nil values but map does not?
compactMap unwraps optionals and discards nils, while map keeps nils as they are. See execution_table rows 2 and 4 where nils are discarded.
What happens if all elements are nil?
compactMap returns an empty array because all nils are discarded. This is shown by the exit_note where only non-nil values remain.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the resulting array after step 3?
A[1, nil, 3]
B[1]
C[1, 3]
D[1, 3, nil]
💡 Hint
Check the 'Resulting Array' column at step 3 in the execution_table.
At which step does compactMap discard the first nil value?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Is nil?' and 'Action' columns in the execution_table.
If the input array had no nils, how would the final unwrapped array compare to the original?
AIt would be empty
BIt would be the same as the original array without optionals
CIt would contain only nils
DIt would contain fewer elements
💡 Hint
Refer to variable_tracker and concept_flow about how compactMap works with non-nil values.
Concept Snapshot
compactMap removes nils from an array of optionals.
Syntax: array.compactMap { $0 }
Returns an array of unwrapped non-nil values.
Useful to clean arrays with optional elements.
map keeps nils; compactMap removes them.
Full Transcript
We start with an array of optional integers, some are nil. Using compactMap, we check each element. If it is not nil, we keep it; if it is nil, we discard it. Step by step, the resulting array grows only with non-nil values. At the end, we have an array without any nils. This is different from map, which keeps nils. compactMap is useful to unwrap optionals and clean arrays in one step.