Atakan Atakan - 1 year ago 585
Swift Question

XCode 8 and Swift 3 NSCalendar

I implemented my watch project in Swift and now I should migrate to Swift 3 because of XCode 8. I let XCode 8 to change the source code to Swift 3. However, there are errors in the code and I can not figure it out.

let unitFlags: Calendar = [.hour, .firstWeekday, .monthSymbols, .year, .minute, .firstWeekday]

var calendar = NSCalendar.current
calendar.timeZone = NSTimeZone(identifier: "UTC")!
let components = (calendar as NSCalendar).components(unitFlags, from: reservationDate)

XCode gives error in these lines and I can not understand the problem.

ERROR: Contextual type ' Calendar' cannot be used with array literal

ERROR: Argument labels '(identifier:)' do not match any available overloads

ERROR: Cannot convert value of type 'Calendar' to expected argument type 'NSCalendar.Unit'

Answer Source

First of all, neither NSCalendarUnit in Swift 2 nor Calendar.Component in Swift 3 contain the components firstWeekday and monthSymbols.

In Swift 3 the equivalent of your code is

let unitFlags = Set<Calendar.Component>([.hour, .year, .minute])
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = calendar.dateComponents(unitFlags, from: reservationDate)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download