Question: I want to map over an array of optionals, removing those values that are nil, and mapping non-nil values using another function.

I know I can achieve this by using `compactMap` and then a regular `map`, but I'd like to iterate over the array only once.

I've implemented a `mapNonNils` function to to that:

```swift
// 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)
}

```

but I'd like to know if there's a built-in function, or an easier way to do this.

Thanks.

Answer: 
You can use [`compactMap`](https://developer.apple.com/documentation/swift/array/2957701-compactmap) (which will remove `nil` values) in conjunction with [`flatMap`](https://developer.apple.com/documentation/swift/optional/1540500-flatmap) of the `Optional` (which will call the closure only if the optional is not `nil`, and just return `nil` otherwise), e.g.

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

```

Resulting in:

> 
> [2, 4, 8]
> 
> 
>
I think it's as simple as: 

```
myArray.lazy.compactMap { $0 }.map { /*whatever*/ }

```