在Swift中将map()应用于字典的最干净的方法是什么?

编程入门 行业动态 更新时间:2024-10-09 07:18:27
本文介绍了在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()应用于字典的最干净的方法是什么?

本文发布于:2023-10-19 17:40:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508284.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用于   中将   字典   干净   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!