Swift 3 - Cannot convert value of type Date? to type 'NSDate' in coercion

4.5k views Asked by At

I have a global optional CLLocation variable as follows:

var location : CLLocation? = nil

I want to unwrap and convert the timestamp of the location to NSDate.

location?.timestamp as NSDate

I get the following error

Cannot convert value of type Date? to type 'NSDate' in coercion.

How do I resolve this?

PS: I am a newbie to Swift 3.

1

There are 1 answers

0
Nirav D On BEST ANSWER

Your location property is optional and you are trying to get timestamp from it so that you are getting optional Date? instance i.e the reason you are getting that error.

In Swift 3 use Date instead of NSDate and use if let or guard to unwrapped optional.

if let date = lastSavedLocation?.timestamp {
     print(date)
}