chicobermuda chicobermuda - 18 days ago 5
Swift Question

Change a dictionary's key in Swift

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.

Answer

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" */
Comments