获取 "ambiguous use of 'components' error" while 运行 HKStatisticsCollectionQuery 示例代码

Getting an "ambiguous use of 'components' error" while running HKStatisticsCollectionQuery example code

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

当我在 运行 代码

时,我在锚组件声明中遇到了 Ambiguous use of 'components' 错误

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