Search code examples
swift3nsdatecllocation

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


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.


Solution

  • 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)
    }