Change a dictionary's key in Swift
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" */