在 HealthKit 中工作,我有一系列 HealthKit 锻炼,我需要将它们组织成月份和年份(以便我可以显示 2018 年 1 月、2018 年 2 月等的锻炼)。让我觉得困难的是,我首先需要检查给定月份和年份是否有锻炼,如果没有,我需要为它创建数组,如果有,我需要附加到现有数组。我也不确定最好的数据模型,我正在考虑使用 [[Month:Year]]
但这似乎不是很 Swifty?
guard let workoutsUnwrapped = workouts else { return }
for workout in workoutsUnwrapped {
let calendar = Calendar.current
let year = calendar.component(.year, from: workout.startDate)
let month = calendar.component(.month, from: workout.startDate)
}
最佳答案
我首先创建一个 struct
来保存年和月:
struct YearMonth: Comparable, Hashable {
let year: Int
let month: Int
init(year: Int, month: Int) {
self.year = year
self.month = month
}
init(date: Date) {
let comps = Calendar.current.dateComponents([.year, .month], from: date)
self.year = comps.year!
self.month = comps.month!
}
var hashValue: Int {
return year * 12 + month
}
static func == (lhs: YearMonth, rhs: YearMonth) -> Bool {
return lhs.year == rhs.year && lhs.month == rhs.month
}
static func < (lhs: YearMonth, rhs: YearMonth) -> Bool {
if lhs.year != rhs.year {
return lhs.year < rhs.year
} else {
return lhs.month < rhs.month
}
}
}
现在您可以将其用作字典中的键,其中每个值都是一组锻炼。
var data = [YearMonth: [HKWorkout]]()
现在重复你的锻炼:
guard let workouts = workouts else { return }
for workout in workouts {
let yearMonth = YearMonth(date: workout.startDate)
var yearMonthWorkouts = data[yearMonth, default: [HKWorkout]())
yearMonthWorkouts.append(workout)
data[yearMonth] = yearMonthWorkouts
}
完成此操作后,您的所有锻炼都会按年/月分组。
您可以为字典中的键构建一个按年/月排序的列表。
let sorted = data.keys.sorted()
要将此应用于 TableView ,请使用 sorted
来定义部分的数量。对于每个部分,从相应部分的给定 YearMonth
的 data
获取锻炼数组。
关于swift - 如何最好地在 Swift 中将对象组织成月份和年份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48854418/