我在Swift中有一个包含许多不同日期的数组,我需要按工作日顺序对其进行排序(甚至最好将它们分成一个新数组,其中所有日期都为星期一,星期二...) 最好的方法是什么?
答案 0 :(得分:1)
首先,您必须获得每天的工作日:
let dates: [Date] = ...
let datesWithWeekday: [(date: Date, weekday: Int)] = dates.map {
let weekday = Calendar.current.component(.weekday, from: $0)
return (date: $0, weekday: weekday)
}
然后,您可以使用它做任何想做的事情:
var datesPerWeekday: [Int: [Date]] = [:]
for (date, weekday) in datesWithWeekday {
datesPerWeekday[weekday, default: []].append(date)
}
答案 1 :(得分:1)
如果您不在乎日期在星期几,而只在星期几 ,则可以使用Dictionary(grouping:by:)
将日期数组转换为{{1 }}:
[Int: [Date]]
例如,func weekDay(of date: Date) -> Int {
return Calendar.current.component(.weekday, from: date)
}
let weekDays = Dictionary(grouping: dates, by: weekDay)
print(weekDays)
将为您提供星期六中的所有日期,如果周六没有日期,则为weekDays[7]
。