swift 将一个字典转换成另一个字典的有效方法,其中所有的键都被修改了?

jutyujz0  于 12个月前  发布在  Swift
关注(0)|答案(1)|浏览(105)

在Swift中,我有这样的字典:

let typingAttributes = [
    NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18),
    NSAttributedString.Key.foregroundColor: UIColor.red,
]

字符串
我需要把它转换成另一个字典,其中的键是rawValue。所以类似这样:

[
    NSAttributedString.Key.font.rawValue: UIFont.systemFont(ofSize: 18),
    NSAttributedString.Key.foregroundColor.rawValue: UIColor.red,
]


我知道可以实现这一点的一种方法是创建一个新字典,然后枚举原始字典的所有键并在这个新字典中设置值。
然而,是否有更好的方法类似于数组如何拥有map,reduce等功能?

k7fdbhmy

k7fdbhmy1#

一个解决方案是使用reduce(into:_:)

let output = typingAttributes.reduce(into: [String: Any]()) { partialResult, tuple in
    let newKey = //Get new key from tuple.key
    partialResult[newKey] = tuple.value
}

字符串
在您的例子中,由于您使用NSAttributedString.Key作为字典键,并且您想要原始字符串值:

let newKey = tuple.key.rawValue


这可以简化为:

let output = typingAttributes.reduce(into: [String: Any]()) { 
    $0[$1.key.rawValue] = $1.value
}


带扩展名:

extension Dictionary {
    func mapKeys<T>(_ key: (Key) -> T) -> [T: Value] {
        reduce(into: [T: Value]()) {
            let newKey = key($1.key)
            $0[newKey] = $1.value
        }
    }
}


用法:

let output = typingAttributes.mapKeys { $0.rawValue }


其他样品用途:

//Convert the keys into their int value (it'd crash if it's not an int)
let testInt = ["1": "a", "2": "b"].mapKeys { Int($0)! }
print(testInt)

//Keep only the first character of the keys
let testPrefix = ["123": "a", "234": "b"].mapKeys { String($0.prefix(1)) }
print(testPrefix)

//Fixing keys into our owns, more "readable" and "Swift friendly for instance
let keysToUpdate = ["lat": "latitude", "long": "longitude", "full_name": "fullName"]
let testFixKeys = ["lat": 0.4, "long": 0.5, "full_name": "Seed", "name": "John", "age": 34].mapKeys { keysToUpdate[$0] ?? $0 }
print(testFixKeys)

//etc.

相关问题