无法使用 Calendar.current.dateComponents 检查经过的时间

Unable to check time elapsed with Calendar.current.dateComponents

我想查看从一个时间戳到现在经过了多少秒。我有这个:

Calendar.current.dateComponents([.second], from: userInfo?["timestamp"], to: Date()).second! > preferences["secsToWait"]

但是我收到了这个错误:

Type 'Any' has no member 'second'

将代码更改为:

Calendar.current.dateComponents([Calendar.Component.second], from: userInfo?["timestamp"], to: Date()).second! > preferences["secsToWait"]

将错误消息更改为:

Cannot invoke 'dateComponents' with an argument list of type '([Calendar.Component], from: Any?, to: Date)'

我在上面有这个:

import Foundation;

此代码在 SafariExtensionHandler 内部调用(如果重要的话)。知道是什么原因造成的吗?

您收到此错误是因为 userInfo 的类型为 [AnyHashable : Any]。这意味着 userInfo?["timestamp"] 的结果是 Any? 类型。在看不到您如何存储该信息的情况下,我假设您实际上传递了一个 Date 对象,在这种情况下,您需要先解包时间戳才能使用它。最安全的方法是:

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"]
}

你也可以这样做:

//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"]