以下是接收问题代码的代码行:
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: [])
答案 0 :(得分:1)
Swift 3为现有版本引入了一堆新的值类型
基础课类型,例如Date
的{{1}},NSDate
Calendar
。其中一些原因是
NSCalendar
和let
代替可变和不可变的变体,详情可在
中找到您可以在值类型和相应的var
类型之间架起桥梁
(正如您对NS
所做的那样),以及现有的Foundation API
导入到Swift中,类型会自动桥接。
因此,date as Date
会返回NSCalendar.current
而不是Calendar
NSCalendar
,calendar.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)
// ...
}
请注意,Date
为Comparable
,因此您可以比较日期
直接在now <= date
中。 NSDate
无法做到这一点
(除非你明确地实现它。)