gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:28:18 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com