Swift中如何高效将字典键转为rawValue?有没有类似map的简洁方法?
Swift字典键转换为rawValue的简洁实现方法
你可以利用Swift标准库中Dictionary的init(uniqueKeysWithValues:)初始化方法,结合map来实现这个转换,写法和数组map一样简洁:
let typingAttributes = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.red, ] // 转换为rawValue为键的字典 let rawKeyAttributes = Dictionary(uniqueKeysWithValues: typingAttributes.map { ($0.key.rawValue, $0.value) })
这个方法逻辑直接:先用map把原字典的每个(NSAttributedString.Key, Value)键值对,转换成(String, Value)的元组(NSAttributedString.Key的rawValue为String类型),再通过Dictionary的初始化方法直接构建新字典。由于原字典的键本身唯一,uniqueKeysWithValues完全适用,不会出现键冲突问题。
如果偏好reduce风格的写法,也可以用reduce(into:)实现:
let rawKeyAttributes = typingAttributes.reduce(into: [String: Any]()) { result, pair in result[pair.key.rawValue] = pair.value }
两种方法的效率和手动遍历枚举基本一致,但前者写法更简洁直观,更贴合函数式编程风格。
内容的提问来源于stack exchange,提问作者sudoExclamationExclamation
相关产品推荐
相关产品推荐

