-
-
Save aaronfalls/d7a7754d308ce23b4d24592c483bed95 to your computer and use it in GitHub Desktop.
Adam Preble's DateRange struct (http://adampreble.net/blog/2014/09/iterating-over-range-of-dates-swift/), updated to Swift 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Calendar { | |
func dateRange(start: Date, | |
end: Date, | |
stepUnits: Calendar.Component, | |
stepValue: Int) -> DateRange { | |
let dateRange = DateRange(calendar: self, | |
start: start, | |
end: end, | |
stepUnits: stepUnits, | |
stepValue: stepValue) | |
return dateRange | |
} | |
} | |
struct DateRange: Sequence, IteratorProtocol { | |
var calendar: Calendar | |
var start: Date | |
var end: Date | |
var stepUnits: Calendar.Component | |
var stepValue: Int | |
private var multiplier: Int | |
init(calendar: Calendar, start: Date, end: Date, stepUnits: Calendar.Component, stepValue: Int) { | |
self.calendar = calendar | |
self.start = start | |
self.end = end | |
self.stepUnits = stepUnits | |
self.stepValue = stepValue | |
self.multiplier = 0 | |
} | |
mutating func next() -> Date? { | |
guard let nextDate = calendar.date(byAdding: stepUnits, | |
value: stepValue * multiplier, | |
to: start, | |
wrappingComponents: false) else { | |
return nil | |
} | |
guard nextDate < end else { | |
return nil | |
} | |
multiplier += 1 | |
return nextDate | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment