【问题标题】:Unable to check time elapsed with Calendar.current.dateComponents无法使用 Calendar.current.dateComponents 检查经过的时间
【发布时间】:2019-12-07 04:30:25
【问题描述】:

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

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

但是我收到了这个错误:

类型'Any'没有成员'second'

把代码改成这样:

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

将错误消息更改为:

不能使用类型为“([Calendar.Component], from: Any?, to: Date)”的参数列表调用“dateComponents”

我确实有这个:

import Foundation;

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

【问题讨论】:

    标签: swift safari-app-extension


    【解决方案1】:

    您收到此错误是因为 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"]
    

    【讨论】:

      猜你喜欢
      • 2013-09-10
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多