Change a dictionary's key in Swift

后端 未结 2 1839
旧时难觅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" */
    
    0 讨论(0)
  • 2021-01-19 04:30

    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" */
    
    0 讨论(0)
提交回复
热议问题