Search code examples
swift3nscalendar

Difference between NSCalendar.current and NSCalendar.currentCalendar()


I'm working on accessing healthkit's Heartrate data and through following the documentation here: https://developer.apple.com/reference/healthkit/hksamplequery. They call to use the following code snippet

let calendar = NSCalendar.currentCalendar()
let now = NSDate()
let components = calendar.components([.Year, .Month, .Day], fromDate: now)

However the debugger catches the NSCalendar.currentCalendar() as cannot call value of non-function type calendar. I changed it to NSCalendar.current as suggested by the IDE however then the third line has a problem stating that it cannot use instance member 'calendar' within property initializer.

So my question is what is the difference between NSCalendar.current and NSCalendar.currentCalendar() and what am I doing wrong?

Thanks so much for any help that you can provide.


Solution

  • The difference is that you are using Swift 3 but looking at instructions for Swift 2.x. The APIs have changed. This is the Swift 3 equivalent:

    let calendar = Calendar.current
    let now = Date()
    let components = calendar.dateComponents([.year, .month, .day], from: now)