Reputation: 22946
I have an NSManagedObject
object with:
@NSManaged public var timestamp: NSDate
I needed the time interval between two of these, so I implemented:
let interval = next.timestamp.timeIntervalSince(current.timestamp)
Why does this result in the following error?
'NSDate' is not implicitly convertible to 'Date'; did you mean to use
'as' to explicitly convert?
I'm surprised because both next
and current
are of type NSDate
, and timeIntervalSince()
is an NSDate
method.
It's easily fixed by following the suggestion in the error, but I'd like to understand what going on here:
let interval = next.timestamp.timeIntervalSince(current.timestamp as Date)
In case it matters, this is on Swift 3.0.
Upvotes: 3
Views: 2106
Reputation: 31645
Referring to 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.
If you check timeIntervalSince
method signature, it is func timeIntervalSince(_ anotherDate: Date) -> TimeInterval
, note that anotherDate
date type is Date
(not NSDate
anymore).
For more information about new value types, check this proposal of mutability and foundation value types, there is a bunch of new value types such as: NSData, NSMutableData -> Data, NSIndexPath -> IndexPath, NSNotification -> Notification...
Upvotes: 2