Search code examples
swifthealthkit

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

I'm getting an Ambiguous use of 'components' error at anchor components declaration when I'm running the code


Solution

  • You should use Date, DateComponents and Calendar instead of NSDate, NSDateComponents and NSCalendar. Then the old syntax needs to be updated to latest Swift version. Also you need to change constant(let) interval and anchorComponents to variable(var) as you are changing the values. Below is the fixed snippet,solution:

    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