0
0
Swiftprogramming~5 mins

FlatMap for nested collections in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does flatMap do when used on nested collections in Swift?

flatMap takes a collection of collections and combines them into a single, flat collection by removing one level of nesting.

Click to reveal answer
beginner
Given <code>let numbers = [[1, 2], [3, 4], [5]]</code>, what is the result of <code>numbers.flatMap { $0 }</code>?

The result is [1, 2, 3, 4, 5]. It merges all inner arrays into one single array.

Click to reveal answer
intermediate
How is flatMap different from map when working with nested arrays?

map transforms each element but keeps the nested structure, while flatMap transforms and then flattens one level of nesting.

Click to reveal answer
intermediate
Can flatMap be used to remove nil values from an array of optionals in Swift?

Yes. When used on an array of optionals, flatMap unwraps and removes nil values, returning only non-nil elements.

Click to reveal answer
intermediate
What is the output of this Swift code?<br><pre>let nested = [["a", "b"], ["c"]]
let result = nested.flatMap { $0.map { $0.uppercased() } }</pre>

The output is ["A", "B", "C"]. Each string is uppercased, then all arrays are flattened into one.

Click to reveal answer
What does flatMap do to a nested array in Swift?
ADuplicates each element in the array
BKeeps the nested arrays unchanged
CFlattens one level of nested arrays into a single array
DRemoves all elements from the array
Which method would you use to transform elements but keep the nested structure?
Amap
Bfilter
CflatMap
Dreduce
What happens when flatMap is used on an array of optionals with some nil values?
AIt unwraps and removes <code>nil</code> values
BIt returns an array including <code>nil</code> values
CIt converts all values to strings
DIt throws an error
Given let arr = [[1, 2], [3]], what is the result of arr.map { $0.count }?
A[1, 1]
B[[1, 2], [3]]
C[3]
D[2, 1]
Which Swift method combines mapping and flattening in one step?
Afilter
BflatMap
Cmap
Dreduce
Explain how flatMap works on nested collections in Swift and give a simple example.
Think about turning [[1,2],[3,4]] into [1,2,3,4]
You got /3 concepts.
    Describe the difference between map and flatMap when used on nested arrays.
    Consider what happens to the structure of the array
    You got /3 concepts.