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

标签 arrays swift

我想获取一个结构数组(带有 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/

相关文章:

c - 递归指定字母数

arrays - 没有更多上下文,表达式类型不明确

javascript - 无法返回适当的值

Swift 3 隐式解包选项导致错误的字符串插值

arrays - 结构类型数组的元素创建问题

arrays - 自定义单元格在 TableView 中全白

php - 数组创建德语问题

php - 仅当一个字段作为数组提供时,Laravel Eloquent 才插入多条记录

ios - Swift 单元测试错误 - 找不到架构 i386 的 AWSCore 框架

swift - Swift IBInspectable didSet与获取/设置