是否有内置函数来映射非 nil 元素,并删除数组的 nil 元素?

Is there a built-in function to map over non-nil elements, and remove nil elements of array?

我想映射一个可选数组,删除那些 nil 值,并使用另一个函数映射非 nil 值。

我知道我可以通过使用 compactMap 然后使用常规 map 来实现这一点,但我只想遍历数组一次。

我为此实现了一个 mapNonNils 函数:

// Adapts a function to handle optional input
func adaptForOptional<T, R>(_ originalFunc: @escaping (T) -> R) -> (T?) -> R? {
    return { optionalValue in
        return (optionalValue != nil) ? originalFunc(optionalValue!) : nil
    }
}

// maps over non-nil elements, and remove nils
extension Array {
    func mapNonNils<T, E>(function: @escaping (E) -> T) -> [T] where Element == Optional<E> {
        let adaptedFunction = adaptForOptional(function)
        return self.compactMap(adaptedFunction)
    }
}

// sample function
func double(num: Int) -> Int {
    return num * 2
}

// doubles non-nil elements, and remove nils
func doubleNonNil(_ original: [Int?]) -> [Int] {
    return original.mapNonNils(function: double)
}

但我想知道是否有内置函数或更简单的方法。

谢谢。

我认为这很简单:

myArray.lazy.compactMap { [=10=] }.map { /*whatever*/ }

您可以使用 OptionalcompactMap (which will remove nil values) in conjunction with flatMap(仅当可选项不是 nil 时才会调用闭包,而只是 return nil否则),例如

let values: [Int?] = [1, 2, nil, 4]
let results = values.compactMap { [=10=].flatMap { [=10=] * 2 } }

导致:

[2, 4, 8]