swift - 为什么具有两个 `as Date` 对象的 `timeIntervalSince()` 需要 `NSDate`?

标签 swift date nsdate nstimeinterval

我有一个 NSManagedObject 对象:

@NSManaged public var timestamp: NSDate

我需要两者之间的时间间隔,所以我实现了:

let interval = next.timestamp.timeIntervalSince(current.timestamp)

为什么会出现以下错误?

'NSDate' is not implicitly convertible to 'Date'; did you mean to use
'as' to explicitly convert?

我很惊讶,因为 nextcurrent 都是 NSDate 类型,而 timeIntervalSince()NSDate 方法。

按照错误中的建议很容易修复,但我想了解这里发生了什么:

let interval = next.timestamp.timeIntervalSince(current.timestamp as Date)

万一重要,这是在 Swift 3.0 上。

最佳答案

引用NSDate Apple Documentation :

The Swift overlay to the Foundation framework provides the Date structure, which bridges to the NSDate class. The Date value type offers the same functionality as the NSDate reference type, and the two can be used interchangeably in Swift code that interacts with Objective-C APIs. This behavior is similar to how Swift bridges standard string, numeric, and collection types to their corresponding Foundation classes.

如果查看timeIntervalSince方法签名,是func timeIntervalSince(_ anotherDate: Date) -> TimeInterval,注意anotherDate日期类型是 Date(不再是 NSDate)。

有关新值类型的更多信息,请查看 this proposal在可变性和基础值类型方面,有一堆新的值类型,例如:NSData、NSMutableData -> Data、NSIndexPath -> IndexPath、NSNotification -> 通知...

关于swift - 为什么具有两个 `as Date` 对象的 `timeIntervalSince()` 需要 `NSDate`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40125100/

相关文章:

ios - 使用 swift 提取 AWS DynamoDB 中的数据

ios - 在 Swift 中根据纬度和经度查找城市名称和国家/地区

php - 同时将 Date 加 1 年并减去 1 Day

jQuery DataTables - 英国日期列排序

ios - 使用来自 Parse.com 的 createdAt 日期时的 NSDate 准确性

ios - 带有字符串参数调用的 Swift 枚举函数,带有枚举类的参数

swift - 常量 json 推断有 'AnyObject' ,这可能是意外的

mysql - 比较 MySQL 中的 TIMEDIFF

ios - 静态 NSDate 变量在函数调用之间不断重置

objective-c - 一旦 iOS 中的系统日期发生变化,如何更改带有日期的标签?