如何最好地将对象组织成Swift中的月份和年份?

时间:2018-02-18 17:16:49

标签: swift date

在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)
}

1 个答案:

答案 0 :(得分:5)

我首先创建一个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来定义部分的数量。对于每个部分,从data获取相应部分的给定YearMonth的锻炼数组。