Hi everyone,
I would like to pitch an addition to Foundation's Calendar
API.
Full text is here, and a PR for editorial comments is here.
Introduction
In macOS 14 / iOS 17, Calendar
was rewritten entirely in Swift. One of the many benefits of this change is that we can now more easily create Swift-specific Calendar
API that feels more natural than the existing enumerate
methods. In addition, we are taking the opportunity to add a new field to the DateComponents
type to handle one case that was only exposed via the somewhat esoteric CoreFoundation API CFCalendarDecomposeAbsoluteTime
.
Motivation
The existing enumerateDates
method on Calendar
is basically imported from an Objective-C implementation. We can provide much better integration with other Swift API by providing a Sequence
-backed enumeration.
Proposed solution
We propose a new field on DateComponents
and associated options / units:
extension Calendar {
public enum Component : Sendable {
// .. existing fields
@available(FoundationPreview 0.4, *)
case dayOfYear
}
}
extension DateComponents {
/// A day of the year.
/// For example, in the Gregorian calendar, can go from 1 to 365 or 1 to 366 in leap years.
/// - note: This value is interpreted in the context of the calendar in which it is used.
@available(FoundationPreview 0.4, *)
public var dayOfYear: Int?
}
We also propose a new API on Calendar
to use enumeration in a Sequence
-friendly way:
extension Calendar {
/// Computes the dates which match (or most closely match) a given set of components, returned as a `Sequence`.
///
/// If `direction` is set to `.backward`, this method finds the previous match before the given date. The intent is that the same matches as for a `.forward` search will be found. For example, if you are searching forwards or backwards for each hour with minute "27", the seconds in the date you will get in both a `.forward` and `.backward` search would be 00. Similarly, for DST backwards jumps which repeat times, you'll get the first match by default, where "first" is defined from the point of view of searching forwards. Therefore, when searching backwards looking for a particular hour, with no minute and second specified, you don't get a minute and second of 59:59 for the matching hour but instead 00:00.
///
/// If an exact match is not possible, and requested with the `strict` option, the sequence ends.
///
/// Result dates have an integer number of seconds (as if 0 was specified for the nanoseconds property of the `DateComponents` matching parameter), unless a value was set in the nanoseconds property, in which case the result date will have that number of nanoseconds, or as close as possible with floating point numbers.
/// - parameter start: The `Date` at which to start the search.
/// - parameter components: The `DateComponents` to use as input to the search algorithm.
/// - parameter matchingPolicy: Determines the behavior of the search algorithm when the input produces an ambiguous result.
/// - parameter repeatedTimePolicy: Determines the behavior of the search algorithm when the input produces a time that occurs twice on a particular day.
/// - parameter direction: Which direction in time to search. The default value is `.forward`, which means later in time.
@available(FoundationPreview 0.4, *)
public func dates(startingAt start: Date,
matching components: DateComponents,
matchingPolicy: MatchingPolicy = .nextTime,
repeatedTimePolicy: RepeatedTimePolicy = .first,
direction: SearchDirection = .forward) -> DateSequence
}
extension Calendar {
/// A `Sequence` of `Date`s which match the specified search criteria.
/// - note: This sequence will terminate after a built-in search limit to prevent infinite loops.
@available(FoundationPreview 0.4, *)
public struct DateSequence : Sendable, Sequence {
public typealias Element = Date
public var calendar: Calendar
public var start: Date
public var matchingComponents: DateComponents
public var matchingPolicy: Calendar.MatchingPolicy
public var repeatedTimePolicy: Calendar.RepeatedTimePolicy
public var direction: Calendar.SearchDirection
public init(calendar: Calendar, start: Date, matchingComponents: DateComponents, matchingPolicy: Calendar.MatchingPolicy = .nextTime, repeatedTimePolicy: Calendar.RepeatedTimePolicy = .first, direction: Calendar.SearchDirection = .forward)
public func makeIterator() -> Iterator
public struct Iterator: Sendable, IteratorProtocol {
// No public initializer
public mutating func next() -> Element?
}
}
}
Detailed design
The new Sequence
-based API is a great fit for Swift because it composes with all the existing algorithms and functions that exist on Sequence
. For example, the following code finds the next 3 minutes after August 22, 2022 at 3:02:38 PM PDT, then uses zip
to combine them with some strings. The second array naturally has 3 elements. In contrast with the existing enumerate
method, no additional counting of how many values we've seen and manully setting a stop
argument to break out of a loop is required.
let cal = Calendar(identifier: .gregorian)
let date = Date(timeIntervalSinceReferenceDate: 682869758.712307) // August 22, 2022 at 7:02:38 AM PDT
let dates = zip(
cal.dates(startingAt: date, matching: DateComponents(minute: 0), matchingPolicy: .nextTime),
["1st period", "2nd period", "3rd period"]
)
let description = dates
.map { "\($0.formatted(date: .omitted, time: .shortened)): \($1)" }
.formatted()
// 8:00 AM: 1st period, 9:00 AM: 2nd period, and 10:00 AM: 3rd period
Another example is simply using the prefix
function. Here, it is combined with use of the new dayOfYear
field:
var matchingComps = DateComponents()
matchingComps.dayOfYear = 234
// Including a leap year, find the next 5 "day 234"s
let nextFive = cal.dates(startingAt: date, matching: matchingComps).prefix(5)
/*
Result:
2022-08-22 00:00:00 +0000
2023-08-22 00:00:00 +0000
2024-08-21 00:00:00 +0000 // note: leap year, one additional day in Feb
2025-08-22 00:00:00 +0000
2026-08-22 00:00:00 +0000
*/
The new dayOfYear
option composes with existing Calendar
API, and can be useful for specialized calculations.
let date = Date(timeIntervalSinceReferenceDate: 682898558.712307) // 2022-08-22 22:02:38 UTC, day 234
let dayOfYear = cal.component(.dayOfYear, from: date) // 234
let range1 = cal.range(of: .dayOfYear, in: .year, for: date) // 1..<366
let range2 = cal.range(of: .dayOfYear, in: .year, for: leapYearDate // 1..<367
// What day of the week is the 100th day of the year?
let whatDay = cal.date(bySetting: .dayOfYear, value: 100, of: Date.now)!
let dayOfWeek = cal.component(.weekday, from: whatDay) // 3 (Tuesday)
Source compatibility
The proposed changes are additive and no significant impact on existing code is expected. Some Calendar
API will begin to return DateComponents
results with the additional field populated.
Implications on adoption
The new API has an availability of FoundationPreview 0.4 or later.
Alternatives considered
The DateSequence
API is missing one parameter that enumerateDates
has - a Boolean
argument to indicate if the result date is an exact match or not. In research for this proposal, we surveyed many callers of the existing enumerateDates
API and found only one that did not ignore this argument. Given the greater usability of having a simple Date
as the element of the Sequence
, we decided to omit the value from the Sequence
API. The existing enumerateDates
method will continue to exist in the rare case that the exact-match value is required.
We decided not to add the new fields to the DateComponents
initializer. Swift might add a new "magic with
" operator which will provide a better pattern for initializing immutable struct types with var
fields. Even if that proposal does not end up accepted, adding a new initializer for each new field will quickly become unmanageable, and using default values makes the initializers ambiguous. Instead, the caller can simply set the desired value after initialization.
We originally considered adding a field for Julian days, but decided this would be better expressed as a conversion from Date
instead of from a DateComponents
. Julian days are similar to Date
in that they represent a point on a fixed timeline. For Julian days, they also assume a fixed calendar and time zone. Combining this with the open API of a DateComponents
, which allows setting both a Calendar
and TimeZone
property, provides an opportunity for confusion. In addition, ICU defines a Julian day slightly differently than other standards and our current implementation relies on ICU for the calculations. This discrepency could lead to errors if the developer was not careful to offset the result manually.
Acknowledgments
Thanks to Tina Liu for early feedback on this proposal.