generate an array of dates in swift

To generate an array of dates in Swift, you can use a loop to iterate through a range of dates and append each date to an array. Here is an example:

main.swift
// Define the start and end dates
let startDate = Date()
let endDate = Calendar.current.date(byAdding: .day, value: 7, to: startDate)!

// Define the date formatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

// Generate an array of dates
var dateArray = [Date]()
var currentDate = startDate
while currentDate <= endDate {
    dateArray.append(currentDate)
    currentDate = Calendar.current.date(byAdding: .day, value: 1, to: currentDate)!
}

// Convert the array of dates to an array of formatted strings
let formattedDateArray = dateArray.map { dateFormatter.string(from: $0) }

// Print the result
print(formattedDateArray)
661 chars
22 lines

In this example, we use the Date() function to get the current date as the starting point. We then use the Calendar.current.date(byAdding:to:) function to add 7 days to the start date to define the end date.

We define a date formatter to convert the dates to formatted strings. We then define an empty array to store the generated dates and use a while loop to iterate through the range of dates, appending each date to the array.

Finally, we use the map function to convert the array of dates to an array of formatted strings before printing the result.

gistlibby LogSnag