Skip to main content

Articles, snippets and thoughts about code from Andrew Lord.

Create time intervals with explicit units

Published on · Updated on
1 minute read

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 to me on Twitter.

Thanks for reading and happy coding!

Like what you read? Please share the article.

Avatar of Andrew Lord

Hi, I hope you enjoyed the article. I am Andrew - a builder of apps and developer tools. Articles on the blog focus on all aspects of Android and iOS development using Kotlin and Swift.

Subscribe via RSS