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

时间:2016-08-02 09:28:42

标签: swift3 xcode8 xcode8-beta4

这个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测试版中,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

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

2 个答案:

答案 0 :(得分:28)

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

注意:要使呼叫更简单,您可以省略Calendar.Component前缀。

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

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

答案 1 :(得分:27)

Swift 3和Swift 4:

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

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)