gpt4 book ai didi

swift - 交换字典中值的键?

转载 作者:搜寻专家 更新时间:2023-10-31 21:51:52 24 4
gpt4 key购买 nike

我在 Swift 中有一个字典,看起来像这样:

[
0: "82",
1: "12",
2: "3",
3: "42"
// Etc.
]

假设我想交换值 82 和 3 的键,因此新字典如下所示:

[
0: "3",
1: "12",
2: "82",
3: "42"
// Etc.
]

我该怎么做? (我没有找到任何提示,也不知道如何去做,所以我没有尝试过的代码)

编辑:

我刚刚这样做了:

var first_key = 0
var second_key = 2
var first_value = dict[first_key]!
var second_value = dict[second_key]!
dict[first_key] = second_value
dict[second_key] = first_value

最佳答案

当您必须交换变量时,最简单的方法是使用元组。

如果你想交换xy:

(x, y) = (y, x)

在你的情况下:

(dict[0], dict[2]) = (dict[2], dict[0])

关于swift - 交换字典中值的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31346922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com