Swift:将字典转换为另一个字典(其中所有键都被修改)的有趣方法?

问题描述 投票:0回答:1

在 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]

我知道实现此目的的一种方法是创建一个新字典,然后枚举原始字典的所有键并在这个新字典中设置值。

但是,有没有更好的方法类似于数组具有映射、减少等功能?

swift dictionary nsdictionary
1个回答
0
投票

解决方案是使用

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
}
© www.soinside.com 2019 - 2024. All rights reserved.