Swift / Spring'日期组件'错误

时间:2016-09-08 15:50:05

标签: ios swift

以下是接收问题代码的代码行:

let components: NSDateComponents = calendar.components(unitFlags, fromDate: earliest, toDate: latest, options: [])

问题代码:

'components' produces 'Date Components', not the expected contextual result type 'NSDateComponents'

附加代码:

public func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String {
let calendar = NSCalendar.current
let unitFlags: NSCalendar.Unit = [NSCalendar.Unit.minute, NSCalendar.Unit.hour, NSCalendar.Unit.day, NSCalendar.Unit.weekOfYear, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.second]
let now = NSDate()
let earliest = now.earlierDate(date as Date)
let latest = (earliest == now as Date) ? date : now
let components: NSDateComponents = calendar.components(unitFlags, fromDate: earliest, toDate: latest, options: [])

1 个答案:

答案 0 :(得分:1)

Swift 3为现有版本引入了一堆新的值类型 基础课类型,例如Date的{​​{1}},NSDate Calendar。其中一些原因是

  • 提供正确的值语义,
  • NSCalendarlet代替可变和不可变的变体,
  • 更多" Swifty"的API。

详情可在

中找到

您可以在值类型和相应的var类型之间架起桥梁 (正如您对NS所做的那样),以及现有的Foundation API 导入到Swift中,类型会自动桥接。

因此,date as Date会返回NSCalendar.current而不是Calendar NSCalendarcalendar.components返回DateComponents 而不是NSDateComponents

有时,Xcode迁移器可以为您解决这些问题。如果不, 你必须查找新类型及其方法。

在您的情况下,Swift 3端口看起来像这样:

func timeAgoSinceDate(date: Date, numericDates: Bool) -> String {
    let calendar = Calendar.current
    let components: Set<Calendar.Component> = [.minute, .hour, .day, .weekOfYear, .month, .year, .second]
    let now = Date()
    let (earliest, latest) = (now <= date) ? (now, date) : (date, now)
    let dateComponents = calendar.dateComponents(components, from: earliest, to: latest)

    // ...
}

请注意,DateComparable,因此您可以比较日期 直接在now <= date中。 NSDate无法做到这一点 (除非你明确地实现它。)