在HealthKit工作,我有一系列的HealthKit锻炼,需要将其组织到一个月和年度(以便我可以展示2018年1月,2018年2月,等等(。让我想到的是,我首先需要检查是否有一个月和一年的锻炼,如果没有,我需要为其创建数组,如果我需要附加到现有数组。我也不确定最佳数据模型,我正在考虑使用[[Month:Year]]
,但这似乎不是很笨拙吗?
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()
要将其应用于表视图,请使用sorted
来定义各节的数量。对于每个部分,获取相应部分的给定YearMonth
的data
锻炼数组。