gpt4 book ai didi

arrays - 将结构数组(带日期)拆分为按月分组的二维数组

转载 作者:行者123 更新时间:2023-11-30 11:58:23 26 4
gpt4 key购买 nike

我想获取一个结构数组(带有 date 属性),并将该数组拆分为一个数组数组,其中每个子数组包含日期位于同一日历月的项目。

我只是不知道如何拆分/分组它们等等......

我可以创建一个 var 数组 并迭代该数组来存放项目,但我相信有一种更好(更实用、更快速)的方法来做到这一点。

最佳答案

这里速度非常快:

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)]]

关于arrays - 将结构数组(带日期)拆分为按月分组的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47533716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com