我想在字典中的所有键上映射一个函数.我希望像下面这样的东西会起作用,但过滤器不能直接应用于字典.实现这一目标的最简洁方法是什么?
I'd like to map a function on all keys in the dictionary. I was hoping something like the following would work, but filter cannot be applied to dictionary directly. What's the cleanest way of achieving this?
在这个例子中,我试图将每个值加 1.然而,这对于这个例子来说是偶然的 - 主要目的是弄清楚如何将 map() 应用于字典.
In this example, I'm trying to increment each value by 1. However this is incidental for the example - the main purpose is to figure out how to apply map() to a dictionary.
var d = ["foo" : 1, "bar" : 2] d.map() { $0.1 += 1 } 推荐答案Swift 4+
好消息!Swift 4 包含一个 mapValues(_:) 方法,该方法构造具有相同键但不同值的字典副本.它还包括一个 filter(_:) 重载,它返回一个 Dictionary 和 init(uniqueKeysWithValues:) 和 init(_:uniquingKeysWith:) 初始值设定项,用于从任意元组序列创建 Dictionary.这意味着,如果您想同时更改键和值,您可以这样说:
Good news! Swift 4 includes a mapValues(_:) method which constructs a copy of a dictionary with the same keys, but different values. It also includes a filter(_:) overload which returns a Dictionary, and init(uniqueKeysWithValues:) and init(_:uniquingKeysWith:) initializers to create a Dictionary from an arbitrary sequence of tuples. That means that, if you want to change both the keys and values, you can say something like:
let newDict = Dictionary(uniqueKeysWithValues: oldDict.map { key, value in (key.uppercased(), value.lowercased()) })还有用于将字典合并在一起、替换缺失元素的默认值、对值进行分组(将集合转换为数组字典,由将集合映射到某个函数的结果作为键)等的新 API.
There are also new APIs for merging dictionaries together, substituting a default value for missing elements, grouping values (converting a collection into a dictionary of arrays, keyed by the result of mapping the collection over some function), and more.
在提案讨论期间,SE-0165,介绍了这些功能,我多次提出这个 Stack Overflow 答案,我认为绝对数量的赞成有助于证明需求.所以感谢您帮助 Swift 变得更好!
During discussion of the proposal, SE-0165, that introduced these features, I brought up this Stack Overflow answer several times, and I think the sheer number of upvotes helped demonstrate the demand. So thanks for your help making Swift better!
更多推荐
在 Swift 中将 map() 应用于字典的最干净的方法是什么?
发布评论