I want to check how many seconds passed since one timestamp to now. I have this:
Calendar.current.dateComponents([.second], from: userInfo?["timestamp"], to: Date()).second! > preferences["secsToWait"]
But I'm getting this error:
Type 'Any' has no member 'second'
Changing the code to this:
Calendar.current.dateComponents([Calendar.Component.second], from: userInfo?["timestamp"], to: Date()).second! > preferences["secsToWait"]
changes the error message to:
Cannot invoke 'dateComponents' with an argument list of type '([Calendar.Component], from: Any?, to: Date)'
I do have this on top:
import Foundation;
This code is called inside SafariExtensionHandler
(if it matters). Any idea of what's causing it?
You are getting this error because userInfo
is of type [AnyHashable : Any]
. This means that the result of userInfo?["timestamp"]
is of type Any?
. Without seeing how you are storing that info I assume you are actually passing a Date
object in, in which case you need to unwrap the timestamp before you can use it. The safest way would be:
if let timestamp = userInfo?["timestamp"] as? Date {
//Do whatever you were going to do with
Calendar.current.dateComponents([.second], from: timestamp, to: Date()).second! > preferences["secsToWait"]
}
You could also just do:
//This will crash if the value is nil or if it's not actually a Date
Calendar.current.dateComponents([.second], from: userInfo!["timestamp"] as! Date, to: Date()).second! > preferences["secsToWait"]