Skip to content

Instantly share code, notes, and snippets.

@cprovatas
Created March 8, 2018 16:40
Show Gist options
  • Save cprovatas/651a89b27744f48bab82426f26fe7f6f to your computer and use it in GitHub Desktop.
Save cprovatas/651a89b27744f48bab82426f26fe7f6f to your computer and use it in GitHub Desktop.
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