Reputation: 20590
Given the dictionary:
let dictionary = [ "one": 1, "two": 2, "three": 3]
I want to create a new version with one of the items removed based on its key. So I'm trying to use...
let dictionaryWithTwoRemoved = dictionary.filter { $0.0 != "two" }
... which achieves what I want HOWEVER the two dictionaries have differing types...
`dictionary` is a `[String: Int]`
`dictionaryWithTwoRemoved` is a `[(key: String, value: Int)]`
Which is consequently making my life difficult.
If I try to cast like so...
let dictionaryWithThreeRemoved = dictionary.filter { $0.0 != "three" } as! [String: Int]
...I get the following WARNING...
Cast from '[(key: String, value: Int)]' to unrelated type '[String : Int]' always fails
and the code also crashes with EXC_BAD_INSTRUCTION at runtime.
Help!
Upvotes: 0
Views: 1289
Reputation: 26
If you want an extension method to help you remove the values here you go...
extension Dictionary {
func removingValue(forKey key: Key) -> [Key: Value] {
var mutableDictionary = self
mutableDictionary.removeValue(forKey: key)
return mutableDictionary
}
}
Upvotes: 1
Reputation:
You can use reduce
to do this.
//: Playground - noun: a place where people can play
import Cocoa
let dictionary = [ "one": 1, "two": 2, "three": 3]
let newDictionary = dictionary.reduce([:]) { result, element -> [String: Int] in
guard element.key != "two" else {
return result
}
var newResult = result
newResult[element.key] = element.value
return newResult
}
Upvotes: 1