Swift turns an array into a grouped dictionary

I have an array of objects Transaction

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

One of the properties Transactionis NSDate. I want to convert my array to a dictionary

var transactions: [NSDate: Array<Transaction>]

If all transactions on this date will be in the array with the date as the key.

I know how to iterate over each element of my array and manually assign it to the right key, but I wonder if there is an elegant function for this.

+4
source share
2 answers

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 can define this as an array extension. Sort of:

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) })
    })
  }
}
+2
source

I am printing this in the dark since you did not provide a lot of details in your question. You need to improvise:

// Get the list of distinct dates
var dates = [NSDate]()
for tran in returnedArray {
    if !dates.contains(tran.transactionDate) {
        dates.append(tran.transactionDate)
    }
}

// Now group according to date
var result = [NSDate : Array<Transaction>]()
for d in dates {
    let transactions = returnedArray.filter { $0.transactionDate == d } 
    result[d] = transactions
}
+2
source

Source: https://habr.com/ru/post/1598044/


All Articles