交换键和值的字典扩展 - Swift 4.1

Noa*_*der 4 swap dictionary function swift swift-extensions

字典扩展 - 交换字典键和值

斯威夫特 4.1,Xcode 9.3

我想创建一个函数来获取Dictionary并返回所述字典,但将其值作为键,将其键作为其各自的值。到目前为止,我已经做了一个函数来做到这一点,但我无法将它变成extensionfor 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
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

 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]
Run Code Online (Sandbox Code Playgroud)

理想的:

 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]
Run Code Online (Sandbox Code Playgroud)

我如何实现这个理想?


vad*_*ian 6

Dictionary 的扩展可能看起来像这样,value成为键的必须约束为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)
Run Code Online (Sandbox Code Playgroud)