Mango Snippets » #5

Swift: The Direction of Date.distance(to:)

The official document of Date.distance(to:) says it:

Returns the distance from this date to another date, specified as a time interval.

But it has never been clear to me positive distance means whether the left side date is earlier or later.

So this tip is dedicated to myself: Date.distance(to:) is the opposite of minus. The distance positive when the left side date is earlier.

$ swift
  1> let now = Date()
now: Date = {}
  2> let oneHourLater = now.advanced(by: 3600)
oneHourLater: Date = {}
  3> let distance = now.distance(to: oneHourLater)
distance: TimeInterval = 3600