Tometoyou
Tometoyou

Reputation: 8386

How to flatten optional array of heterogenous values

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?

Upvotes: 0

Views: 152

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236458

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]

Upvotes: 1

Related Questions