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

编程入门 行业动态 更新时间:2024-10-09 05:15:49
本文介绍了在 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:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508283.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用于   中将   字典   干净   方法

发布评论

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

>www.elefans.com

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