[英]How to order an array of diffrent Dates by Weekday in Swift
我在 Swift 中有一个包含许多不同日期的数组,我需要按工作日对它们进行排序(或者甚至更好地将它们每个拆分成一个新数组,一个包含星期一星期二的所有日期......)什么是最好的方法来做到这一点?
First, you have to get the weekday for each day:首先,您必须获得每一天的工作日:
let dates: [Date] = ...
let datesWithWeekday: [(date: Date, weekday: Int)] = dates.map {
let weekday = Calendar.current.component(.weekday, from: $0)
return (date: $0, weekday: weekday)
}
Then you can do anything you want with it:然后你可以用它做任何你想做的事情:
var datesPerWeekday: [Int: [Date]] = [:]
for (date, weekday) in datesWithWeekday {
datesPerWeekday[weekday, default: []].append(date)
}
If you don't care about which week the dates are in and only the days of the week, you can use Dictionary(grouping:by:)
to turn the array of dates into a [Int: [Date]]
:如果你不关心日期在哪一周,只关心星期几,你可以使用
Dictionary(grouping:by:)
将日期数组转换为[Int: [Date]]
:
func weekDay(of date: Date) -> Int {
return Calendar.current.component(.weekday, from: date)
}
let weekDays = Dictionary(grouping: dates, by: weekDay)
print(weekDays)
For example, weekDays[7]
will give you all the dates that are on a Saturday, or nil
if there is no dates on Saturday.例如,
weekDays[7]
将提供星期六的所有日期,如果星期六没有日期,则为nil
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.