我有一个异类数组,看起来是这样的:

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

我想把它展平成一个数组[1,2,3]。我该怎么做?我可以用什么方式使用compactMap { $0 }吗?

最佳答案

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]

关于swift - 如何扁平化异构值的可选数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52166674/

10-08 23:38