Swift 中如何实现可迭代遍历的 Date Range

发布
更新
字数 256
阅读 2 分钟
阅读量 650

我们可以使用 Range 结构来定义一个连续值的范围,包括下限值,但不包括最大值。同时很方便的判断一个值是否在该范围内:

let underFive = 0.0..<5.0

underFive.contains(3.14)
// true
underFive.contains(6.28)
// false
underFive.contains(5.0)
// false

参考文档 https://developer.apple.com/documentation/swift/range Using a Range as a Collection of Consecutive Values https://developer.apple.com/documentation/swift/range#Using-a-Range-as-a-Collection-of-Consecutive-Values 当 Range 成员是整数时或者符合 Stridable 协议 https://developer.apple.com/documentation/swift/strideable/,即可以用 for..in 迭代遍历。 如文档所说

Because floating-point types such as Float and Double are their own Stride types, they cannot be used as the bounds of a countable range. If you need to iterate over consecutive floating-point values, see the stride(from:to:by:) function.

Date 已经符合 Stridable 协议,定义了自己的 Stride 类型

extension Date {
    typealias Stride = TimeInterval
}

所以我们如果需要迭代遍历一个 Date Range,可以先定义一个 stride,也就是迭代的幅度,然后再使用 stride(from:to:by:) 方法进行遍历

let oneDay: Date.Stride = 24 * 60 * 60
let range = stride(from: Calendar.current.startOfDay(for: .now), to: Date().advanced(by: 5 * oneDay), by: oneDay)

range.forEach { date in
    print(date)
}