将一个字典转换为另一个修改所有键的字典的有效方法?

问题描述 投票: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个回答
2
投票

解决方案是使用

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