let calendar = NSCalendar.current
let interval = NSDateComponents()
interval.day = 7
// Set the anchor date to Monday at 3:00 a.m.
let anchorComponents = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: NSDate())
let offset = (7 + anchorComponents.weekday - 2) % 7
anchorComponents.day -= offset
anchorComponents.hour = 3
我在运行代码时在锚定组件声明中误用了'components'错误
答案 0 :(得分:0)
您应该使用Date
,DateComponents
和Calendar
而不是NSDate
,NSDateComponents
和NSCalendar
。然后,旧语法需要更新为最新的Swift
版本。另外,在更改值时,还需要将常量(let
)interval
和anchorComponents
更改为变量(var
)。下面是固定的代码段,
let calendar = Calendar.current
var interval = DateComponents()
interval.day = 7
// Set the anchor date to Monday at 3:00 a.m.
var anchorComponents = calendar.dateComponents([.day, .month, .year, .weekday], from: Date())
let offset = (7 + (anchorComponents.weekday ?? 0) - 2) % 7
anchorComponents.day = (anchorComponents.day ?? 0) - offset
anchorComponents.hour = 3