Swift NSDate Extension Error: Mutating isn't valid on methods in classes or class-bound protocols

Swift NSDate Extension Error: Mutating isn't valid on methods in classes or class-bound protocols

我正在尝试扩展 NSDate,但遇到两个错误:

extension NSDate { //'mutating' isn't valid on methods in classes or class-bound protocols
    mutating func addMonth() {
        let calendar = NSCalendar.currentCalendar()
        let component = NSDateComponents()
        component.month = 1
        self = calendar.dateByAddingComponents(component, toDate: self, options: []) //Cannot assign to value: 'self' is immutable
    }
} 

我的猜测是 NSDate 是 class 而不是 Swift 类型,并且错误指出 mutating 在 [=18= 中的方法上是不可能的]是的。如果我 return 值并分配给它一切正常但我想知道这不起作用的确切原因以及是否有更好的解决方法。

NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).

NSDate Documentation

因为 NSDate 对象是不可变的,所以您不能随意将一个月加到一。您可以将扩展程序修改为 return 从现有日期开始的新 NSDate 对象,添加一个月:

extension NSDate {
    func addMonth() -> NSDate? {
        let calendar = NSCalendar.currentCalendar()
        let component = NSDateComponents()
        component.month = 1
        let newDate = calendar.dateByAddingComponents(component, toDate: self, options: [])
        return newDate
    }
}