在Swift中将map()应用于字典的最干净的方法是什么? [英] What's the cleanest way of applying map() to a dictionary in Swift?

查看:102
本文介绍了在Swift中将map()应用于字典的最干净的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字典中的所有键上映射一个功能.我曾希望像下面这样的东西可以工作,但是过滤器不能直接应用于字典.实现此目的的最干净的方法是什么?

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()应用于字典的最干净的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆