Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary Extension that Swaps Keys & Values - Swift 4.1

Dictionary Extension - Swap Dictionary Keys & Values

Swift 4.1, Xcode 9.3

I want to make a function that would take Dictionary and return said dictionary, but with its values as the keys and its keys as its respective values. So far, I have made a function to do this, but I cannot for the life of me make it into an extension for Dictionary.


My Function

func swapKeyValues<T, U>(of dict: [T : U]) -> [U  : T] {
    let arrKeys = Array(dict.keys)
    let arrValues = Array(dict.values)
    var newDict = [U : T]()
    for (i,n) in arrValues.enumerated() {
        newDict[n] = arrKeys[i]
    }
    return newDict
}

Example of Usage:

 let dict = [1 : "a", 2 : "b", 3 : "c", 4 : "d", 5 : "e"]
 let newDict = swapKeyValues(of: dict)
 print(newDict) //["b": 2, "e": 5, "a": 1, "d": 4, "c": 3]

Ideal:

 let dict = [1 : "a", 2 : "b", 3 : "c", 4 : "d", 5 : "e"]

 //I would like the function in the extension to be called swapped()
 print(dict.swapped()) //["b": 2, "e": 5, "a": 1, "d": 4, "c": 3]

How do I accomplish this ideal?


like image 258
Noah Wilder Avatar asked Dec 14 '22 17:12

Noah Wilder


1 Answers

A extension of Dictionary could look like this, the value which becomes the key must be constrained to Hashable

extension Dictionary where Value : Hashable {

    func swapKeyValues() -> [Value : Key] {
        assert(Set(self.values).count == self.keys.count, "Values must be unique")
        var newDict = [Value : Key]()
        for (key, value) in self {
            newDict[value] = key
        }
        return newDict
    }
}

let dict = [1 : "a", 2 : "b", 3 : "c", 4 : "d", 5 : "e"]
let newDict = dict.swapKeyValues()
print(newDict)
like image 179
vadian Avatar answered Jan 01 '23 18:01

vadian