My first time in Swift: AFSwiftDateExtension

Finally I had enough time to start working on SWIFT, AFSwiftDateExtension is an NSDate extension that makes working with date an easy task.

My first project in SWIFT was a little app that I’ve made for a client. At the very first lines of coding I started to think: “OMG it will take so much time to finish this easy app”, about 30 minutes later ” I must redo all my application in SWIFT”.
SWIFT is not cool, is super cool.
SWIFT is designed around safety, optionals (kind of weird at the first sight) and static typing really helps into make cleaner and safer code avoiding common errors.
In the last few months I’ve worked really hard on an app that uses a lot of calendrical operations and I’ve created a tons of methods to help me doing calendrical calculation. Method such as adding days, comparing dates, create dates from single components etc.
SWIFT comes with a really nice and powerful feature: operator overloading. In Obj-c to compare dates we are stuck on methods like -isEqualToDate, -earlierDate:, -laterDate:, -compare:. On the other hand in SWIFT using operators overloading is possible to use common compare operators.

There is more!

Inspired by this line of mysterious code in Apple SWIFT guide “let oneInch =” in the Computed Properties chapter, I told myself to start thinking how to achieve the same result but with time units and maybe override + and – operators to add/remove time components from a date.

From that thinkering comes an extension on Int that makes easy translate a simple integer in a time measurement unit with a value.
During my reasearch I’ve found also this inspiring article that really helped me out.

public enum TimeUnitMeasure {
    case Seconds
    case Minutes
    case Hours
    case Days
    case Weeks
    case Months
    case Years
public struct TimeFrame {
    var value: Int
    var unitMeasure: TimeUnitMeasure
    private func dateComponents(): NSDateComponents {
      let cmpts = NSDateComponents()
      switch (self.unitMeasure) {
      case .Seconds:
       cmpts.second = value
      case .Minutes:
       cmpts.minute = value
      case .Hours:
       cmpts.hour = value
      case .Days: = value
      case .Weeks:
       cmpts.weekOfYear = value
      case .Months:
       cmpts.month = value
      case .Years:
       cmpts.year = value
      default: = value
    return cmpts

In the enumeration TimeUnitMeasure I’ve defined a unit of measure for time, the structure TimeFrame represents a time window that is composed by a value and a unit of measure, to create a TimeFrame instance we can use the provided member wise initializer. The most interesting part is the private method dateComponents(). This method returns an NSDateComponent with components set to the TimeFrame value.

extension Int {
    var seconds: TimeFrame {
      return TimeFrame(value: self, unitMeasure:.Seconds);
    var minutes: TimeFrame {
      return TimeFrame(value: self, unitMeasure:.Minutes);
    var hours: TimeFrame {
      return TimeFrame(value: self, unitMeasure:.Hours);
    var days: TimeFrame {
      return TimeFrame(value: self, unitMeasure:.Days);
    var weeks: TimeFrame {
      return TimeFrame(value: self, unitMeasure:.Weeks);
    var months: TimeFrame {
      return TimeFrame(value: self, unitMeasure:.Months);
    var years: TimeFrame {
      return TimeFrame(value: self, unitMeasure:.Years);

The extension on Int declare some computed properties that return a TimeFrame structure initilized by using as a value the value of the Int and the unit based on the property called. For instance the property -seconds will return a TimeFrame with Seconds as time unit measure.

Now with a TimeFrame structure I can overload some operators to do basic maths between NSDate instances and TimeFrame instances.

Overloading an operator is an easy task

func + (left: NSDate, right: TimeFrame) -> NSDate? {
    return NSCalendar.currentCalendar().dateByAddingComponents(right.dateComponents(), toDate: left, options: nil)

Here we oveloaded the + operator to make addition between an NSDate and a TimeFrame like this:
nsdateInstance + 3.days
Precedence rules first resolve 3.days returning a TimeFrame and later it will add the two using the + operator.

This extension ( AFSwiftDateExtension ) has grown and now comes with a lot of more features, such as:

  • Compare dates using common compare operators: >, >=, <, <=
  • Get interval between dates using that custom operator >-<
  • Add date components by using aritmethic operators
  • Curryed functions
  • Create dates directly from components
  • Subscripting to acces date components

AFSwiftDateExtension SWIFT extension on NSDate

AFSwiftDateExtension is released under MIT license and can be downloaded from github.

Sorry, the comment form is closed at this time.

Related Posts