我有一个如下所示的异构数组:
let array: [Any] = [
[1, 2, nil],
3
]
我想将其展平为一个数组[1,2,3]。我怎样才能做到这一点?我可以以某种方式使用compactMap { $0 }
吗?
答案 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]