1

I am trying to write an extension where NSDate can be changed to the another date. I want to make an extension which will modify self.

I've check different methods but cannot find how to modify self I am trying something like that but it doesn't work.

extension NSDate {
    func changeDate(unitType: NSCalendarUnit, number: Int, date: NSDate) {

        self.laterDate(NSCalendar.currentCalendar().dateByAddingUnit(
            .Day,
            value: number,
            toDate: date,
            options: []
        )!)
    }
}

In another file I am doing something like that:

let date = NSDate()
// set date to tomorrow
date.changeDate(.Day, number: 1, date: date)

What is the solution?

Danny
  • 3,975
  • 4
  • 22
  • 35

1 Answers1

3

From the NSDate reference (emphasis added):

Date objects are immutable, ...

and therefore you cannot mutate self in an extension method. You'll have to return the new date as another NSDate object, e.g.

extension NSDate {

    func changedDate(unitType: NSCalendarUnit, number: Int) -> NSDate {
        return self.laterDate(NSCalendar.currentCalendar().dateByAddingUnit(
            .Day,
            value: number,
            toDate: self,
            options: []
            )!)
    }
}

var date = NSDate()
date = date.changedDate(.Day, number: 1)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382