Swift将一个数组转换为一个分组的字典[重复](Swift turn an Array into a grouped Dictionary [duplicate])

编程入门 行业动态 更新时间:2024-10-25 19:29:02
Swift将一个数组转换为一个分组的字典[重复](Swift turn an Array into a grouped Dictionary [duplicate])

这个问题在这里已有答案:

如何按Swift 10答案 中的数组元素进行分组

我有一个Transaction对象数组

var returnedArray: Array<Transaction> = [a, b, c, d]

Transaction的一个属性是NSDate 。 我想将我的数组转换为字典

var transactions: [NSDate: Array<Transaction>]

此日期的所有事务都将在以日期为关键字的数组中。

我知道如何遍历我的数组的每个元素并手动将其分配给正确的键,但我想知道是否有一个优雅的功能来做到这一点。

This question already has an answer here:

How to group by the elements of an array in Swift 12 answers

I have an Array of Transaction objects

var returnedArray: Array<Transaction> = [a, b, c, d]

One of the properties of Transaction is an NSDate. I want to convert my Array into a Dictionary

var transactions: [NSDate: Array<Transaction>]

Where all the transactions on that date will be in an Array that has the date as the key.

I know how to loop through each element of my array and manually assign it to the right key but i'm wondering if there is an elegant function to do that.

最满意答案

日期形成一组

var setOfDates = Set (returnedArray.map (transDate))

您可以从一系列对中创建字典:

var result = Dictionary (dictionaryLiteral: setOfDates.map { (date:NSDate) in return (date, returnedArray.filter { date == $0.transDate }) }

您可以将其定义为数组扩展。 就像是:

extension Array { func splitBy<Key:Hashable> (keyMaker: (T) -> Key) -> Dictionary<Key, T> { let theSet = Set (self.map (keyMaker)) return Dictionary (dictionaryLiteral: theSet.map { (key:Key) in return (key, self.filter { key == keyMaker($0) }) }) } }

The dates form a set

var setOfDates = Set (returnedArray.map (transDate))

You can create a dictionary from a sequence of pairs:

var result = Dictionary (dictionaryLiteral: setOfDates.map { (date:NSDate) in return (date, returnedArray.filter { date == $0.transDate }) }

You could define this as an array extension. Something like:

extension Array { func splitBy<Key:Hashable> (keyMaker: (T) -> Key) -> Dictionary<Key, T> { let theSet = Set (self.map (keyMaker)) return Dictionary (dictionaryLiteral: theSet.map { (key:Key) in return (key, self.filter { key == keyMaker($0) }) }) } }

更多推荐

本文发布于:2023-08-02 23:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1382461.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   字典   Swift   turn

发布评论

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

>www.elefans.com

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