Swap keys for values ​​in a dictionary?

I have a dictionary in Swift that looks like this:

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

      

And let's say I want to swap keys for values ​​82 and 3, so the new dictionary looks like this:

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

      

How should I do it? (I didn’t find any hints and have no idea how to do this, so I don’t have the code I tried with this)

EDIT:

I just did this:

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

      

+3


source to share


4 answers


The basic idea is to create a temporary variable to store one of the values ​​as they are exchanged.

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

      



Or you can use the global swap function for this (which does the same internally).

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

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

      

+5


source


When you have to change variables, the easiest way is to use tuples.

If you want to exchange x

and y

:

(x, y) = (y, x)

      



In your case:

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

      

+6


source


You can do something like this by simply changing the values,

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
}

      

The dict value is now new, with the values ​​you wanted. Or you can also add a category to the dictionary, for example

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)

      

Note, you don't really need to pass a pointer.

+2


source


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"]
      

Run codeHide result


0


source







All Articles