Adding special syntax for down casting with as-keyword in compactMap/flatMap by defining currying

Hi!

I catch myself on the following pattern:

[CustomStringConvertable]().flatMap{$0 as? String}.count

Most of the time, I could pass functions to .flatMap(self.functionName) which is useful and even shorter than common passing of closure with parameters.

However, as?! operator doesn't support currying.

Is there any discussion or pitch for this functionality?

Thanks!

Possible syntax

.flatMap(as?(String)) or even .flatMap(as? String)

Implementation

struct ABC {
    static func example() {
        let a = [CustomStringConvertible]().flatMap(To.as(String.self))
        let b = a.flatMap(Cast<String>.as) // Baby Yoda
    }
}

struct To<From> {
    var value: From
    init(_ value: From) {
        self.value = value
    }
    
    static func `as`<T>(_ to: T.Type) -> (From) -> Optional<T> { { $0 as? T} }
}

struct Cast<T> {
    static func `as`<F>(_ from: F) -> (F) -> Optional<T> { { $0 as? T } }
}

Extension for Sequence

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

I don’t know what you’re trying to do, but CustomStringConvertable is almost certainly not what you want.

I don’t know of any such discussions, but a couple of offhand notes:

  1. compactMap would be the semantically appropriate (non-deprecated) tool for such a task.

  2. This would be much easier to achieve with an overload allowing the following syntax (you could write this for yourself even if the community did not rally behind the addition to the standard library): [SomeExistential]().compactMap(as: String.self)

4 Likes