Swift3:内部延期设定时间

Swift 3: Internal Extension to Set Time

我的这个内部日期扩展似乎在 Swift 3:

中不再有效
internal extension DateComponents {
    func to12pm() {
        self.hour = 12
        self.minute = 0
        self.second = 0
    }
}

错误信息是:

Cannot assign to property: 'self' is immutable

如何在 Swift 3 中实现此目的?

附加信息(如果需要):它被这个日期扩展调用:

func endOfWeek(_ weekday: Int) -> Date? {
    guard
        let cal = Calendar.current,
        var comp: DateComponents = (cal as Calendar).components([.weekOfYear], from: self)
        else {
            return nil
    }
    comp.weekOfYear = 1
    comp.day -= 1
    comp.to12pm()
    return (cal as NSCalendar).date(byAdding: comp, to: self.startOfWeek(weekday)!, options: [])!
} 

Swift3:

现在看起来像这样
func endOfWeek(_ weekday: Int) -> Date? {
    let cal = Calendar.current
    var comp = cal.dateComponents([.weekOfYear], from: self)
    comp.weekOfYear = 1
    comp.day? -= 1
    //This does not have the "comp.to12pm()" that the Swift 2 version did
    return cal.date(byAdding: comp, to: self.startOfWeek(weekday)!)!
}

DateComponents 现在是一个结构,这就是它抛出该错误的原因:

Cannot assign to property: 'self' is immutable

您需要从 self 创建一个新的变量,更改它并return它如下:

extension DateComponents {
    var to12pm: DateComponents {
        var components = self
        components.hour = 12
        components.minute = 0
        components.second = 0
        components.nanosecond = 0
        return components
    }
}