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

标签 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)
}

最佳答案

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

关于swift - 如何最好地在 Swift 中将对象组织成月份和年份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48854418/

相关文章:

javascript - insideHTML 在 setInterval 上不改变

php - Laravel - 从数据库中的日期开始只取年份

php - 我需要从 mysql 数据库获取日期并打印今天和获取日期之间的差异

ios - 如何在 Swift 中遵守 Strideable 协议(protocol)?

ios - KVO 全局范围

ios - 如何在 swift 3 的其他功能中使用服务器响应和数据

Excel 文本函数始终返回格式

安卓:日期(年、月、日)

ios - 将对象用作核心数据对象字段类型

ios - 使用 use_frameworks 安装 Facebook SDK!节肢动物