这个问题在这里已有答案:
如何按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 answersI 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) }) }) } }更多推荐
发布评论