Skip to main content

Create time intervals with explicit units


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 {

// They make very readable call sites

I hope the article was useful. If you have any feedback or questions please feel free to reach out.

Thanks for reading!

Like what you read? Please share the article.

Avatar of Andrew Lord


Andrew Lord

A software developer and tech leader from the UK. Writing articles that focus on all aspects of Android and iOS development using Kotlin and Swift.

Want to read more?

Here are some other articles you may enjoy.