Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Swift中将对象组织为月份和年份?_Swift_Date - Fatal编程技术网

如何在Swift中将对象组织为月份和年份?

如何在Swift中将对象组织为月份和年份?,swift,date,Swift,Date,在HealthKit工作时,我有一系列HealthKit训练,我需要按月和按年组织(以便我可以显示2018年1月、2018年2月等的训练)。让我感到困难的是,我首先需要检查给定月份和年份是否有训练,如果没有,我需要为其创建数组,如果有,我需要附加到现有数组。我也不确定最好的数据模型,我曾考虑使用[[Month:Year]],但这似乎不是很快 guard let workoutsUnwrapped = workouts else { return } for workout in workout

在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 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
        }
    }
}
现在重复你的训练:

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()

要将此应用于表视图,请使用
排序
定义节数。对于每个部分,从相应部分的给定
YearMonth
data
中获取训练数组。

对于这样的事情,我并不真正担心“Swift”,我更关心如何最好地排序日期。这意味着问你打算如何处理这些日期?你主要是按时间顺序工作的吗?如果是这样,请按YYYYMMDD执行,无论使用何种语言。您是否希望主要与“逐年”合作?您可以(但不可以)按MMYYYY或MMDDYYYY排序。先告诉我们(和你自己),然后再考虑如何使你的代码“快速”。(不要害怕只做有效的事情。如果这5种代码——忽略最后的结束括号——对你有用,那么好吗?谢谢你,我想做的是使用一个部分填充一个表格视图来分割每个月的训练。除了@rmaddy提供的答案外,还检查这个答案:
return(lhs.year,lhs.month)<(rhs.year,rhs.month)
从Swift 4开始使用init(分组:by:)而不是for循环。我认为使用
日历(标识符:。gregorian)
可能更安全,而不是
日历。当前
。感谢您采用这种优雅的方法。发布的@JoshHomann链接已经失效,这(当前)是一个工作副本:
let sorted = data.keys.sorted()