Created
March 8, 2018 16:40
-
-
Save cprovatas/651a89b27744f48bab82426f26fe7f6f to your computer and use it in GitHub Desktop.
trim null values out of a dictionary in Swift 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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