运行HKStatisticsCollectionQuery示例代码时获得“模糊使用'组件'错误”

时间:2019-01-20 06:08:57

标签: swift health-kit

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'错误

1 个答案:

答案 0 :(得分:0)

您应该使用DateDateComponentsCalendar而不是NSDateNSDateComponentsNSCalendar。然后,旧语法需要更新为最新的Swift版本。另外,在更改值时,还需要将常量(letintervalanchorComponents更改为变量(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