Wah*_*hib -1 arrays date swift
我有一本这样的字典:
var dictionary : [Date: [[Objects]]]
Run Code Online (Sandbox Code Playgroud)
我需要创建一个包含特定年份特定月份的所有日期的数组。当我指定年份和月份时,结果将是这样的:
但在此之前是我创建的变量:
let year: Int = 2020
let month: Int = 5
var array : [Date] =[]
Run Code Online (Sandbox Code Playgroud)
结果可能是这样的:
array = [date1, date2, date3, date10, date25, date30] // There is only these days for the fifth month in the dictionary
Run Code Online (Sandbox Code Playgroud)
该数组将在初始字典中仅包含 2020 年第五个月的日期。
这是我尝试过但失败的方法:
let dateFormatter = DateFormatter()
dateFormatter = "MM dd yyyy" // to have the numbers of the month and not strings
func arrayOfdays(month: Int, year: Int) -> [Date] {
for day in dictionary {
if month == 5 && year == 2020 {
let date = "day month year"
array.append(date)
}
}
return array
}
Run Code Online (Sandbox Code Playgroud)
我是新手,我知道这种方法很好,但绝对不是实施。
感谢您的帮助。
您需要的是过滤字典键。只需获取年份和月份组件并将它们与所需的组件进行比较:
let yearMonth = DateComponents(year: year, month: month)
let array: [Date] = dictionary.keys.filter {
Calendar.current.dateComponents([.year, .month], from: $0) == yearMonth
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |