在 swift 中,如何创建一个数组,其中包含与第一个数组中存在的一个月中所有天数相对应的所有数字?

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)

我是新手,我知道这种方法很好,但绝对不是实施。

感谢您的帮助。

Leo*_*bus 6

您需要的是过滤字典键。只需获取年份和月份组件并将它们与所需的组件进行比较:

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)

  • 是的,这是一个更好的解决方案 (2认同)
  • @Leo 谢谢Leo Dabus,过滤器是一个被低估的解决方案。这往往是我们没有考虑到的解决方案。 (2认同)