我正在尝试扩展 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
是一个类而不是 Swift 类型,并且错误状态是 mutating
在类中的方法上是不可能的。如果我返回该值并为其分配一切正常,但我想知道这不起作用的确切原因以及是否有更好的解决方法。
最佳答案
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
对象是不可变的,所以您不能随意将一个月加到一。您可以修改您的扩展以从现有日期返回一个新的 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
}
}
关于Swift NSDate 扩展错误 : Mutating isn't valid on methods in classes or class-bound protocols,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185749/