我想获取一个结构数组(带有date
属性)并将该数组拆分为一个数组数组,其中每个子数组包含具有相同日历月中日期的项目。
我无法理解如何分割/分组等等......
我可以创建一个var array
并按照我的方式迭代存放项目的数组,但我相信有更好的(更多功能,更Swifty)方法。
答案 0 :(得分:0)
这里非常快:
struct Withdate {
let value: String
let month: Month
}
enum Month: Int {
case Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
}
let firstArray = [Withdate(value: "111", month: .Jan), Withdate(value: "112", month: .Jan), Withdate(value: "441", month: .Apr), Withdate(value: "442", month: .Apr), Withdate(value: "991", month: .Sep), Withdate(value: "992", month: .Sep)]
var objectsDict = [Month: [Withdate]]()
firstArray.forEach { if objectsDict[$0.month] == nil { objectsDict[$0.month] = [Withdate]() }
objectsDict[$0.month]!.append($0) }
let finalArray = Array(objectsDict.values.map{ $0 })
print(finalArray) // will return:
[[main.Withdate(value: "111", month: main.Month.Jan), main.Withdate(value: "112", month: main.Month.Jan)], [main.Withdate(value: "441", month: main.Month.Apr), main.Withdate(value: "442", month: main.Month.Apr)], [main.Withdate(value: "991", month: main.Month.Sep), main.Withdate(value: "992", month: main.Month.Sep)]]