在字典中交换值的键?

时间:2015-07-10 17:33:29

标签: swift

我在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

4 个答案:

答案 0 :(得分:6)

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

如果您想交换xy

(x, y) = (y, x)

在你的情况下:

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

答案 1 :(得分:5)

基本思路是创建一个临时变量,以便在交换时保存其中一个值。

let tmp = dict[0]
dict[0] = dict[2]
dict[2] = tmp

或者您可以使用全局交换功能(在内部执行相同的操作)。

var dict = [
    0: "82",
    1: "12",
    2: "3",
    3: "42"
]

swap(&dict[0], &dict[2])

答案 2 :(得分:2)

你可以做这样的事情来简单地交换价值,

var dict = [
    0: "82",
    1: "12",
    2: "3",
    3: "42"
    // Etc.
]
if  let value = dict[key], let existingValue = dict[newKey] {
    dict[key] = existingValue
    dict[newKey] = value
}

现在,dict的值是新的,带有你想要的值。或者,您也可以在字典上添加类别,

extension Dictionary {
    mutating func swap(key1: Key, key2: Key) {
        if  let value = self[key1], let existingValue = self[key2] {
            self[key1] = existingValue
            self[key2] = value
        }

    }
}


dict.swap(0, key2: 2)
print(dict)

注意,你真的不需要传递指针。

答案 3 :(得分:0)



var random = ["LAX":"Los Angeles", "JFK":"New York"]


func flip <T, U>(_ dictionary: Dictionary<U, T>) -> Dictionary<T, U> {

 
    let arrayOfValues: [T] = Array(dictionary.values)
    let arrayOfKeys: [U] = Array(dictionary.keys)

    var newDictionary: [T: U] = [:]
    
    for i in 0...arrayOfValues.count-1 {
       
        newDictionary[arrayOfValues[i]] = arrayOfKeys[i]
        
    }
    
    return newDictionary
    
}

flip(random) // You will get ["Los Angeles": "LAX", "New York": "JFK"]
&#13;
&#13;
&#13;

相关问题