In Swift, I have this type of dictionary:
let typingAttributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18),
NSAttributedString.Key.foregroundColor: UIColor.red,
]
I need to convert it into another dictionary where the key is the rawValue. So something like this:
[
NSAttributedString.Key.font.rawValue: UIFont.systemFont(ofSize: 18),
NSAttributedString.Key.foregroundColor.rawValue: UIColor.red,
]
One way I know I can achieve this is by creating a new dictionary, then enumerating all the keys of the original dictionary and setting the values in this new dictionary.
However, is there a better way similar to how Arrays have things like map, reduce etc?
A solution is to use
reduce(into:_:):In your case, since you are using
NSAttributedString.Keyfor the dictionary keys, and you want the raw string value:Which can then be simplified into:
With an extension:
Usages:
Other samples uses: