如何更改特定值的字典键?我不能只是改为dict[i]
,dict[i+1]
因为这会改变该特定键的值.并且没有dict.updateKeyForValue()
像这样的东西dict.updateValueForKey()
.
因为我的密钥都是Int
乱码,所以我无法通过循环修改整个键值对,因为我可能会覆盖循环尚未到达的一对.有更简单的方法吗?觉得我错过了一些明显的东西.
斯威夫特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" */
斯威夫特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" */