In swift, how to create an array with all the numbers corresponding to all the days of a month that are present in the first array?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error In swift, how to create an array with all the numbers corresponding to all the days of a month that are present in the first array? on this date .

I have a dictionary like this:

var dictionary : [Date: [[Objects]]]

I need to create an array that contains all the date of a specific month of a specific year. The result will be like this when i specify the year and the month:

but before here are the variables that i havec created:

let year: Int = 2020
let month: Int = 5

var array : [Date] =[]

the result can be like this:

array = [date1, date2, date3, date10, date25, date30] // There is only these days for the fifth month in the dictionary

the array will contains only the dates of the fifth month of 2020 in the initial dictionary.

Here is how i have tried but i failed:

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
}

I am very novice, and i know that the approach is good but absolutly not the implementation.

thank you for your help.

Answer

What you need is to filter the dictionary keys. Just get the year and month components and compare them to the desired ones:

let yearMonth = DateComponents(year: year, month: month)
let array: [Date] = dictionary.keys.filter {
    Calendar.current.dateComponents([.year, .month], from: $0) == yearMonth
}