/* 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. */