SE-0218 — Introduce compactMapValues to Dictionary

I may be missing something, but this extension seems to work just fine:

extension Sequence {
    func compact<Dummy>() -> [Dummy] where Element == Dummy? {
        return compactMap({$0})
    }
}

let xs = [1, 2, nil, 4, 5]
let ys = xs.compact()
print(ys)  // [1, 2, 4, 5]

(One definite usability downside is ys.compact() will still show up in autocompletion and the resulting error is rather unfriendly: "Generic parameter 'Dummy' could not be inferred".)

3 Likes