This micro-library is made for you if:

  • You have ever written something like this:
let interval: TimeInterval = 10 * 60Copy the code

To represent 10 minutes.

Usage

Basics

Time is not just a bunch of Double conversion functions. The main advantage of it is that all time units are strongly-typed. So, for example:

let tenMinutes = 10.minutesCopy the code

Here tenMinutes will actually be of type Interval

(not to be confused with Foundation’s TimeInterval). There are seven time units available, from nanoseconds to days:

public extension Double {
    
    var seconds: Interval<Second> {
        return Interval<Second>(self)}var minutes: Interval<Minute> {
        return Interval<Minute>(self)}var milliseconds: Interval<Millisecond> {
        return Interval<Millisecond>(self)}var microseconds: Interval<Microsecond> {
        return Interval<Microsecond>(self)}var nanoseconds: Interval<Nanosecond> {
        return Interval<Nanosecond>(self)}var hours: Interval<Hour> {
        return Interval<Hour>(self)}var days: Interval<Day> {
        return Interval<Day>(self)}}Copy the code

Conversions

Time intervals are easily convertible:

let twoMinutesInSeconds = 2.minutes.inSeconds // Interval<Second>Copy the code

You can also convert intervals to Foundation‘s TimeInterval, if needed:

let timeInterval = 5.minutes.timeIntervalCopy the code

You can also use converted(to:) method:

let fiveSecondsInHours = 5.seconds.converted(to: Hour.self) // Interval<Hour>
// or
let fiveSecondsInHours: Interval<Hour> = 5.seconds.converted(a)Copy the code

Although, in my opinion, you would rarely need to.

Creating your own time units

If, for some reason, you need to create your own time unit, that’s super easy to do:

public enum Week : TimeUnit {
    
    public static var toTimeIntervalRatio: Double {
        return 604800}}Copy the code

Now you can use it as any other time unit:

let fiveWeeks = Interval<Week>(5)Copy the code

For the sake of convenience, don’t forget to write those handy extensions:

public enum Week : TimeUnit {
    
    public static var toTimeIntervalRatio: Double {
        return 604800}}extension Interval {
    
    public var inWeeks: Interval<Week> {
        return converted()}}extension Double {
    
    public var weeks: Interval<Week> {
        return Interval<Week>(self)}}extension Int {
    
    public var weeks: Interval<Week> {
        return Interval<Week>(Double(self))}}Copy the code

Disclaimer

Time is in very early stage. Some stuff will probably be broken at some point.