Generic Swift Dictionary Extension for nil filtering

Viewed 2162

I'm looking for a type safe, generic version of this answer.

This is the method signature I'm looking for:

extension Dictionary where Value == Optional<T> {
    func filterNil() -> <Key, T>
}

Is there any way to express this in Swift 3?

Edit:

My motivation for creating a Dictionary with optional values is that I need something like this:

struct User {
    var mail: String?
    var name: String?

    func marshaled() -> [String: Any] {
        return [
            "mail": mail,
            "name": name
        ].filterNil()
    }
}

I much prefer the dictionary literal to creating an empty dictionary and filling the values manually.

1 Answers
Related