如何在Swift的两个日期之间获得一系列日期?

Ahm*_*d F 1 date swift

考虑到我们有一个函数签名:

func datesRange(from: Date, to: Date) -> [Date]
Run Code Online (Sandbox Code Playgroud)

应该采用from日期和to日期实例,并返回一个包含其参数之间的日期(天)的数组.

我尝试了什么:

由于我尝试给出了正确的结果,我宁愿将其添加为答案,因此:

我为什么要问?

"如果你已经提出了一个解决方案,为什么你要问它呢?!"

因为我认为我的解决方案有其他选择会更优雅,而不是做一个标准的迭代(可以设计为函数式编程风格或类似的东西).

Ahm*_*d F 8

你可以像这样实现它:

func datesRange(from: Date, to: Date) -> [Date] {
    // in case of the "from" date is more than "to" date,
    // it should returns an empty array:
    if from > to { return [Date]() }

    var tempDate = from
    var array = [tempDate]

    while tempDate < to {
        tempDate = Calendar.current.date(byAdding: .day, value: 1, to: tempDate)!
        array.append(tempDate)
    }

    return array
}
Run Code Online (Sandbox Code Playgroud)

用法:

let today = Date()
let nextFiveDays = Calendar.current.date(byAdding: .day, value: 5, to: today)!

let myRange = datesRange(from: today, to: nextFiveDays)
print(myRange)
/*
[2018-03-20 14:46:03 +0000,
 2018-03-21 14:46:03 +0000,
 2018-03-22 14:46:03 +0000,
 2018-03-23 14:46:03 +0000,
 2018-03-24 14:46:03 +0000,
 2018-03-25 14:46:03 +0000]
*/
Run Code Online (Sandbox Code Playgroud)