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
.
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
}
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]
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?
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)