I have this function:
func flatten<Key: Hashable, Value>(dict: Dictionary<Key, Optional<Value>>) -> Dictionary<Key, Value> {
var result = [Key: Value]()
for (key, value) in dict {
guard let value = value else { continue }
result[key] = value
}
return result
}
As you can see, it transforms a [Key: Value?]
dictionary into a [Key: Value]
one (without the optional).
I wanted to extend the Dictionary
class with a new method only for classes which value is an Optional
of any type, but I am unable to add constraints to the generic parameters of the dictionary.
This is what I tried:
extension Dictionary where Value: Optional<Any> {
func flatten() -> [Key: Any] {
var result = [Key: Any]()
for (key, value) in self {
guard let value = value else { continue }
result[key] = value
}
return result
}
}
But fails with error:
Type 'Value' constrained to non-protocol type 'Optional<Any>'