Change a dictionary's key in Swift

后端 未结 2 1880
旧时难觅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:30

    Swift 3

    func switchKey(_ 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(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" */
    

提交回复
热议问题