在Swift中更改字典的键 [英] Change a dictionary's key in Swift

查看:502
本文介绍了在Swift中更改字典的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改特定值的字典键?我不能将 dict [i] 更改为 dict [i + 1] ,因为这会更改。而且没有 dict.updateKeyForValue()喜欢有一个 dict.updateValueForKey()

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().

由于我的密钥是 Int 的全部不按顺序,我无法通过循环修改整个键值对,因为我可以覆盖一个循环尚未到达的对。有更简单的方法吗?感觉像我缺少一些明显的东西。

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.

推荐答案

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

这篇关于在Swift中更改字典的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆