Created
August 23, 2019 09:16
-
-
Save phlippieb/05a42f3b708dbf0ed7ca16097191c27e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Given an array with optional sub-arrays, how can I flatten the array? | |
Example: | |
Given [[1, 2], nil, [3]] | |
Expect [1, 2, 3] | |
Solution: | |
First compact-map, then flat-map. | |
*/ | |
let array = [[1, 2], nil, [3]] | |
let flattened = array | |
.compactMap { $0 } // Remove nil sub-arrays | |
.flatMap { $0 } // Flatten the sub-arrays | |
/* | |
Note: | |
If I try to do the flat-map first, Swift thinks I'm mistakenly using `flatMap` where I meant to use `compactMap`; | |
`flatMap` then removes the nil sub-arrays, and the subsequent `compactMap` has no effect. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment