Xcode 8 beta 4: Calendar.Unit vs Calendar.Component
Asked Answered
B

2

26

This Swift 3 code worked until XCode 8 beta 3:

let calendar = Calendar.current
let anchorComponents = calendar.components([Calendar.Unit.day, Calendar.Unit.month, Calendar.Unit.year, Calendar.Unit.hour], from: self)

In Xcode 8 beta 4 Calendar.Unit appears to be renamed to Calendar.Component.

Now this code

let calendar = Calendar.current
let anchorComponents = calendar.components([Calendar.Component.day, Calendar.Component.month, Calendar.Component.year, Calendar.Component.hour], from: self)

produces the compiler error cannot convert value of type Calendar.Component to NSCalendar.Unit

Am I doing anything wrong or is this a bug?

Brahe answered 2/8, 2016 at 9:28 Comment(0)
H
31

In the Swift version shipped with Xcode 8 beta 4, components has been renamed to dateComponents.

Note: to make the call simpler, you can omit the Calendar.Component prefix.

let anchorComponents = calendar.dateComponents([.day, .month, .year, .hour], from: self)

The error message you got is a bit misleading, I guess the compiler was struggling with type inference.

Haslam answered 2/8, 2016 at 12:28 Comment(1)
If you're not using this in a Date extension you have to replace self by a proper date object.Haslam
M
31

Swift 3 and Swift 4:

In this example you could also prepare your unitFlags from/to date:

let calendar = NSCalendar.current
let unitFlags = Set<Calendar.Component>([.day, .month, .year, .hour])
let anchorComponents = calendar.dateComponents(unitFlags, from: startDate as Date,  to: endDate as Date)
Mathematics answered 21/9, 2016 at 7:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.