Swift NSDate 扩展错误 : Mutating isn't valid on methods in classes or class-bound protocols

标签 swift nsdate mutating-function

我正在尝试扩展 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 Documentation

因为 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/

相关文章:

iphone - 使用24-12小时格式的xcode在“TimePicker”中设置NSDate

ios - 对 HTTPS 域的 alamofire 请求与对 HTTP 域的请求有什么不同吗?

ios - UILabel 中的 NSAttributedString 尾部截断

ios - 有没有办法检测 NSDate 在哪个千年?

swift - 为什么 mutating function next 在迭代后不会改变结构(符合 Sequence 和 IteratorProtocol)?

ios - Swift 中的 "mutating"函数和 "inout"参数有什么区别吗?

swift - 具有外部检测的变异函数要变异的变量

swift - 带按钮和 UITableView 的快速下拉菜单

javascript - 使用 JavaScript 中的 Firebase 云函数更新标签栏项目徽章的 ios 静默推送通知的有效负载

cocoa-touch - 更改 Cocoa 单元测试的系统日期