【问题标题】:TimeInterval in SwiftSwift 中的时间间隔
【发布时间】:2016-06-28 13:11:39
【问题描述】:

您好,我需要将 Objective-c 中的这段代码转换为 Swift 但我遇到了 Date 和 TimeInterval 对象的问题。 斯威夫特版本:3 Xcode 版本:8.0 测试版

编辑: 这是一个可能的解决方案吗?

编辑 2:

【问题讨论】:

  • 您必须在NSDate 的实例上调用timeIntervalSince,但不能在NSDate 类上调用。否则,它不会返回NSTimerInterval(双精度),而是返回NSDate。无论如何,我认为当你调用 NSDate.timeIntervalSince(currentDate) 时 XCode 必须返回一个错误,因为它不是类函数。
  • 你能在代码中发布一个例子吗?
  • 我已经发布了代码。
  • @Hoa 没有错误,因为 Swift are curried at static scope 中的实例方法。即NSDate.timeIntervalSince返回一个(Date) -> (Date) -> TimeInterval——其中第一个参数是调用函数的Date实例,第二个参数是Date函数的Date参数。
  • @AngeloPettinelli : 您可以直接使用NSDate().timeIntervalSince... 并在您的编辑代码中删除.init

标签: objective-c xcode swift swift3 xcode8


【解决方案1】:

根据我的评论,您的代码必须是:

private func updateTimer() {
    let currentDate = NSDate()
    let timeInterval = currentDate.timeIntervalSince(self.startDate)
    let timerDate = NSDate(timerIntervalSince1970: timeInterval)
}

private func updateTimer() {
    //we don't have to create the variable "currentDate".
    let timeInterval = NSDate().timeIntervalSince(self.startDate)
    let timerDate = NSDate(timerIntervalSince1970: timeInterval)
}

【讨论】:

  • 完美 我在编辑问题时发布了它!谢谢!
【解决方案2】:

对于 Swift 3 使用日期:

private func updateTimer() {
    let currentDate = Date()
    let timeInterval = currentDate.timeIntervalSince(self.startDate)
    let timerDate = Date(timeIntervalSince1970: timeInterval)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多