Search code examples
iosswiftnsdateswift-extensions

How to change self in NSDate extension Swift?


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?


Solution

  • 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)