0
0
Swiftprogramming~5 mins

CompactMap for optional unwrapping in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does compactMap do in Swift?

compactMap takes a collection and transforms its elements, removing any nil values from the result. It unwraps optionals safely and returns an array of non-optional values.

Click to reveal answer
beginner
How is compactMap different from map when dealing with optionals?

map transforms elements but keeps optionals in the result, while compactMap unwraps optionals and removes nil values, returning only non-optional results.

Click to reveal answer
beginner
Example: What is the result of ["1", "2", "three", "4"].compactMap { Int($0) }?

The result is [1, 2, 4]. The string "three" cannot be converted to an integer, so it becomes nil and is removed.

Click to reveal answer
intermediate
Why use compactMap instead of a loop with manual unwrapping?

compactMap is concise, safe, and expressive. It avoids errors from forced unwrapping and makes code easier to read by handling optionals automatically.

Click to reveal answer
intermediate
Can compactMap be used to filter and transform elements at the same time?

Yes! compactMap lets you transform elements and automatically removes any that become nil, effectively filtering and mapping in one step.

Click to reveal answer
What does compactMap return when applied to an array with some nil values?
AA single optional value
BAn array including <code>nil</code> values
CAn array without the <code>nil</code> values, unwrapped
DA dictionary of values
Which method keeps nil values in the result when transforming an array of optionals?
AcompactMap
Bmap
Cfilter
Dreduce
What is the output of ["10", "abc", "30"].compactMap { Int($0) }?
A[10, 30]
B["10", "abc", "30"]
C[10, nil, 30]
Dnil
Why is compactMap safer than forced unwrapping when dealing with optionals?
AIt automatically removes <code>nil</code> values without crashing
BIt forces unwraps all values
CIt converts all values to strings
DIt ignores all optionals
Can compactMap be used to both filter and transform an array?
ANo, it neither filters nor transforms
BNo, it only filters
CNo, it only transforms
DYes, it filters out <code>nil</code> and transforms elements
Explain how compactMap helps in unwrapping optionals in Swift collections.
Think about how it handles nil and non-nil values during transformation.
You got /4 concepts.
    Describe a real-life scenario where using compactMap is better than using map with forced unwrapping.
    Consider converting user input strings to numbers.
    You got /4 concepts.