I have an array of tuples "recentPayments", that contains a date and a subscriptionItem(custom class I made). I would like to order this into groups by month. I used Dictionary(grouping: by) to do this and it works and outputs into "transactionsByMonth" variable, that contains a string for the month and year and this corresponds to a recent payment item. The only problem is this outputs in an irregular order, the months aren't in order. I have tried many things but could not fix it, and can find no similar things online. Thanks for any help.
var recentPayments: [(Date, SubscriptionItem)] = []
@State var transactionsByMonth: [String: [(Date, SubscriptionItem)]] = [:]
func getPaymentsByMonths() {
transactionsByMonth = Dictionary(grouping: recentPayments) { $0.0.formatted(.dateTime.year().month()) }
}
CodePudding user response:
Dictionary
, is by definition, not ordered. If you want an ordered dictionary, check out OrderedDictionary
in swift-collections