Created
June 18, 2017 16:28
-
-
Save asmallteapot/bcbb356222e46cd35208fcf484339b11 to your computer and use it in GitHub Desktop.
Code koan: Dividing a `DateInterval` into sub-intervals by `Calendar.Component`s in Swift 4
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
extension Calendar { | |
func divide(interval dividend: DateInterval, by component: Calendar.Component, value divisor: Int) -> [DateInterval]? { | |
var intervals: [DateInterval] = [] | |
var previousDate = dividend.start | |
while | |
let nextDate = self.date(byAdding: component, value: divisor, to: previousDate), | |
dividend.contains(nextDate) | |
{ | |
let interval = DateInterval(start: previousDate, end: nextDate) | |
intervals.append(interval) | |
previousDate = nextDate | |
} | |
return intervals | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The initial implementation ignores the remainder for
DateInterval
s that cannot be evenly divided.