【问题标题】:NSTimeInterval to ComponentsNSTimeInterval 到组件
【发布时间】:2014-10-04 09:49:37
【问题描述】:

我正在尝试将 this answer 中的 Objective-C 代码以及在 this answer 中找到的更正转换为 Swift:

var theTimeInterval = NSTimeInterval()
var calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)

var date1 = NSDate()
var date2 = NSDate(timeInterval: theTimeInterval, sinceDate: date1)

var unitFlags = NSCalendarUnit(UInt.max)
var info = calendar.components(unitFlags, fromDate:date1, toDate:date2, options:0)

但是,在最后一行,Xcode 给了我一个莫名其妙的错误:

调用中的额外参数“toDate”

我通过命令单击查看了NSCalendar 的代码,我使用的函数签名似乎与它的components 方法完全匹配。那我做错了什么?

【问题讨论】:

标签: swift nsdate nsdatecomponents nstimeinterval


【解决方案1】:

我相信这是 Swift 4 的正确实现。注释:

  • 在组件中使用任何你需要的东西
  • 看起来参数“选项”已被删除(请参阅the docs
    var theTimeInterval = TimeInterval()
    var calendar = Calendar(identifier: .gregorian)

    var date1 = Date()
    var date2 = Date(timeInterval: theTimeInterval, since: date1)

    //NSCalendarUnit from objc are Calendar.Component in swift
    var components: Set<Calendar.Component> = [.hour, .minute, .second]
    var info = calendar.dateComponents(components,
                                       from: date1, to: date2)

【讨论】:

    【解决方案2】:

    这对我有用:

    var info = calendar.components(unitFlags, fromDate: date1, toDate: date2, options: NSCalendarOptions(0))
    

    您必须编写 NSCalentarOptions 枚举。

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多