Noa*_*der 4 swap dictionary function swift swift-extensions
我想创建一个函数来获取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
}
 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]
我如何实现这个理想?
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)
| 归档时间: | 
 | 
| 查看次数: | 1382 次 | 
| 最近记录: |