Skip to content

Instantly share code, notes, and snippets.

@phlippieb
Created August 23, 2019 09:16
Show Gist options
  • Save phlippieb/05a42f3b708dbf0ed7ca16097191c27e to your computer and use it in GitHub Desktop.
Save phlippieb/05a42f3b708dbf0ed7ca16097191c27e to your computer and use it in GitHub Desktop.
/*
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