I noticed that when comparing two instances of Swift Datewith ==they correspond to the same date when the difference is DateComponents.nanosecondsless than 30. For example:
let calendar = Calendar(identifier: .gregorian)
let startComps = DateComponents(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, nanosecond: 0)
let endComps = DateComponents(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, nanosecond: 29)
let startDate = calendar.date(from: startComps)!
let endDate = calendar.date(from: endComps)!
print(startDate == endDate)
//prints true, changing 29 to 30 prints false
The behavior is the same when compared with startDate.compare(endDate) == .orderedSame. I could not find mention of this in the docs or headings. Is there a logical reason for 30 nanoseconds to be a cutoff for equality?
source
share