How can I change a dictionary's key for a particular value? I can't just change dict[i]
to dict[i+1]
because that changes the value for that particular key. And there's no dict.updateKeyForValue()
like there is a dict.updateValueForKey()
.
Because my keys are Int
's and all out of order, I can't modify the entire key-value pair by looping through because I may override a pair that the loop hasn't reached yet. Is there a simpler way? Feel like I'm missing something obvious.
Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.
Any type that conforms to the Hashable protocol can be used as a dictionary's Key type, including all of Swift's basic types. You can use your own custom types as dictionary keys by making them conform to the Hashable protocol.
The Python dictionary keys() method returns all the keys in a dictionary. This method returns keys as a special object over which you can iterate. keys() accepts no arguments. We add the keys() method after the dictionary name.
Removing Key-Value Pairs To remove a key-value pair from a dictionary, set the value of a key to nil with subscript syntax or use the . removeValue() method. To remove all the values in a dictionary, append . removeAll() to a dictionary.
Swift 3
func switchKey<T, U>(_ myDict: inout [T:U], fromKey: T, toKey: T) {
if let entry = myDict.removeValue(forKey: fromKey) {
myDict[toKey] = entry
}
}
var dict = [Int:String]()
dict[1] = "World"
dict[2] = "Hello"
switchKey(&dict, fromKey: 1, toKey: 3)
print(dict) /* 2: "Hello"
3: "World" */
Swift 2
func switchKey<T, U>(inout myDict: [T:U], fromKey: T, toKey: T) {
if let entry = myDict.removeValueForKey(fromKey) {
myDict[toKey] = entry
}
}
var dict = [Int:String]()
dict[1] = "World"
dict[2] = "Hello"
switchKey(&dict, fromKey: 1, toKey: 3)
print(dict) /* 2: "Hello"
3: "World" */
I'm personally using an extension which imo makes it easier :D
extension Dictionary {
mutating func switchKey(fromKey: Key, toKey: Key) {
if let entry = removeValue(forKey: fromKey) {
self[toKey] = entry
}
}
}
Then to use it:
var dict = [Int:String]()
dict[1] = "World"
dict[2] = "Hello"
dict.switchKey(fromKey: 1, toKey: 3)
print(dict) /* 2: "Hello"
3: "World" */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With