0

I have a heterogenous array that looks like this:

let array: [Any] = [
    [1, 2, nil],
    3
]

I'd like to flatten this to be an array [1, 2, 3]. How can I do this? Can I use compactMap { $0 } somehow?

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • Seems your question was already asked : https://stackoverflow.com/questions/25589605/swift-shortcut-unwrapping-of-array-of-optionals => yes, you, can use `compactMap` – Vinzzz Sep 04 '18 at 12:49
  • @Vinzzz That's not a heterogenous array though, I've updated my code to make it clearer. – Tometoyou Sep 04 '18 at 12:51
  • Then look at the recursive answer to this question : https://stackoverflow.com/questions/24465281/flatten-a-array-of-arrays-in-swift, I doubt any Swift standard operator helps you – Vinzzz Sep 04 '18 at 13:05
  • 1
    possible duplicate of https://stackoverflow.com/a/47544741/2303865 – Leo Dabus Sep 04 '18 at 13:21
  • 2
    Possible duplicate of [Flatten \[Any\] Array Swift](https://stackoverflow.com/questions/47544675/flatten-any-array-swift) – regina_fallangi Sep 04 '18 at 13:28

1 Answers1

1
extension Collection {
    func flatMapped<T>(with type: T.Type? = nil) -> [T] {
        return flatMap { ($0 as? [Any])?.flatMapped() ?? ($0 as? T).map { [$0] } ?? [] }
    }
}

let array: [Any] = [[1, 2, nil],3]
// Use the syntax of your choice
let flattened1: [Int] = array.flatMapped()         //  [1, 2, 3]
let flattened2 = array.flatMapped(with: Int.self)  //  [1, 2, 3] 
let flattened3 = array.flatMapped() as [Int]       //  [1, 2, 3]
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571