为什么带有两个 NSDate 对象的 timeIntervalSince() 需要 as Date?

Why is `as Date` required for `timeIntervalSince()` with two `NSDate` objects?

我有一个 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 -> Notification...