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.
Update: As of Swift 4, you can simply do
It is currently being discussed if
Dictionary
should get acompactMapValues
method which combinesfilter
andmapValues
.(Previous answer:) You can use the same "trick" as in How can I write a function that will unwrap a generic property in swift assuming it is an optional type? and Creating an extension to filter nils from an Array in Swift: define a protocol to which all optionals conform:
Then your dictionary extension can be defined as:
Example: