如何展平异构值的可选数组

时间:2018-09-04 12:44:24

标签: swift

我有一个如下所示的异构数组:

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

我想将其展平为一个数组[1,2,3]。我怎样才能做到这一点?我可以以某种方式使用compactMap { $0 }吗?

1 个答案:

答案 0 :(得分: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]