In Swift, many APIs take a TimeInterval
instead of just a Double
, you need to know they are in seconds. Instead we can add functions that provide them with explicit units and allow us to convert them. It makes for a really readable call site! 👍
extension TimeInterval {
// Hide the calculations from the call site
private static var secondsPerHour: Double { return 60 * 60 }
private static var secondsPerMinute: Double { return 60 }
// Functions to provide time intervals with explicit units
static func hours(_ value: Double) -> TimeInterval {
value * secondsPerHour
}
static func minutes(_ value: Double) -> TimeInterval {
value * secondsPerMinute
}
static func seconds(_ value: Double) -> TimeInterval {
value
}
}
// They make very readable call sites
TimeInterval.hours(3)
TimeInterval.minutes(46)
TimeInterval.seconds(35)
Thanks for reading and happy coding! 🙏