Xcode 8 测试版 4:Calendar.Unit 对比 Calendar.Component

Xcode 8 beta 4: Calendar.Unit vs Calendar.Component

此 Swift 3 代码一直有效到 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)

在 Xcode 8 beta 4 Calendar.Unit 中似乎重命名为 Calendar.Component

现在这段代码

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

产生编译器错误cannot convert value of type Calendar.Component to NSCalendar.Unit

我是不是做错了什么或者这是一个错误?

在 Xcode 8 beta 4 附带的 Swift 版本中,components 已重命名为 dateComponents

注意:为了使调用更简单,可以省略Calendar.Component前缀。

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

您收到的错误消息有点误导,我猜编译器正在努力进行类型推断。

Swift 3 和 Swift 4:

在此示例中,您还可以准备 unitFlags from/to 日期:

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)