Change a dictionary's key in Swift

后端 未结 2 1838
旧时难觅i
旧时难觅i 2021-01-19 03:32

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

2条回答
  •  盖世英雄少女心
    2021-01-19 04:28

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

提交回复
热议问题