16

I have been working on a clock app in Swift and with Xcode 6.3.2 the following code builds and runs just fine.

// Get current time
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | .CalendarUnitNanosecond, fromDate: date)
let hour = components.hour % 12
let minute = components.minute
let second = components.second
let nanosecond = components.nanosecond

However when I load the same project up in Xcode 7.0 beta and make no changes whatsoever, I get an error on the calendar.components line.

Could not find member 'CalendarUnitHour'

I've looked at the documentation and all of the NSCalendarUnit constants are deprecated (in iOS 8.0 it says) but the method description for the components method still says to use them.

I've played around with other NSCalendarUnit auto-complete values but none produce working code and I can't find any recent examples online, perhaps because this is brand new.

Anyone know the new correct way to do this?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
zkarj
  • 657
  • 9
  • 23

2 Answers2

32

Swift 2

The NSCalendarUnit names have changed in Swift 2.

Also, now we have to pass these arguments in an OptionSet, like this:

let components = calendar.components([.Hour, .Minute, .Second, .Nanosecond], fromDate: date)

Swift 3

Many things have changed, according to the Swift API Design Guidelines.

Updated syntax:

let date = Date()
let calendar = Calendar.current()
let components = calendar.components([.hour, .minute, .second, .nanosecond], from: date)

Swift 4

Calendar.current is now a property, and .components has been renamed to .dateComponents. Otherwise it's the same as in Swift 3.

let calendar = Calendar.current
let components = calendar.dateComponents([.hour, .minute, .second, .nanosecond], from: date)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
1

They're now a new protocol. OptionSetType

https://developer.apple.com/library/prerelease/mac/documentation/Swift/Reference/Swift_OptionSetType_Protocol/index.html

brian.clear
  • 5,277
  • 2
  • 41
  • 62
  • why the down vote. This is a common mistake people are making since moving to Swift 2. I'm giving you the technical reason why using the bar | doesn't work anymore!! – brian.clear Oct 13 '15 at 09:00