Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
trim null values out of a dictionary in Swift 4
//Uses only O(n) complexity.
extension Dictionary where Key == String, Value == Any? {
var trimmingNullValues: [String: Any] {
var copy = self
forEach { (key, value) in
if value == nil {
copy.removeValue(forKey: key)
}
}
return copy as [Key: ImplicitlyUnwrappedOptional<Value>]
}
}
//Usage: ["ok": nil, "now": "k", "foo": nil].trimmingNullValues // = ["now": "k"]
//If you dictionary is mutable you could do this and prevent the inefficient copying:
extension Dictionary where Key == String, Value == Any? {
mutating func trimmingNullValues() -> [String: Any] {
forEach { (key, value) in
if value == nil {
removeValue(forKey: key)
}
}
return self as [Key: ImplicitlyUnwrappedOptional<Value>]
}
}
// Usage:
// var dict: [String: Any?] = ["ok": nil, "now": "k", "foo": nil]
// dict.trimmingNullValues() // = ["now": "k"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.