better compactMap

Here’s the code if you want to experiment with it:

import Foundation

extension Collection {
    func nilValuesRemoved<Wrapped>() -> [Wrapped] where Element == Wrapped? {
        self.compactMap { $0 }
    }
}

let optionals = [1, 2, nil, 3, nil]

for nonNilValue in optionals.​nilValuesRemoved() {
    print(nonNilValue)
}
Previous
Previous

if used as an expression

Next
Next

lazy + private(set)