Add convenient compactMap variant to downcast elements to given type

Add convenient compactMap variant to downcast elements to given type.


Since we have "Keypaths as functions" proposal implemented, it is one of steps on a road to explicit functions as parameters in compactMap.
Swift-evolution thread: Discussion thread topic for that proposal


I catch myself on following pattern: filter elements of special type and downcast them to this type.

sequence.compactMap({ $0 as? Type })

This pitch allows us to write:

sequence.compactMap(as: Type) // requires effort from Core team?
// or
sequence.compactMap(as: Type.self) // easy-to-achieve by user.

Proposed solution

extension Sequence {
    func compactMap<ElementOfResult>(as target: ElementOfResult.Type) -> [ElementOfResult] {
        compactMap({$0 as? ElementOfResult})

Detailed design

If we dive a little deeper, then we could find a corner problem.

as(?|!)? // - operator is not a function.

It would be nice if we could use partial applying for it. In that case we could even dismiss this proposal.

static func as<S, T>(_ target: T.Type)(_ source: S)

After adding function above, we could downcast values easily.


Source compatibility

Since we're only adding new functions that are implemented on top of existing functions, I guess, that this is not a problem.

Effect on ABI stability

Not sure.

Effect on API resilience

Not sure.

Alternatives considered

Could be done by user.

1 Like

That links to the forum main page, not to a specific thread.