我正在尝试将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
方法完全匹配。那么我做错了什么?
答案 0 :(得分:0)
我相信这是Swift 4的正确实现。
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)
答案 1 :(得分:-1)
这对我有用:
var info = calendar.components(unitFlags, fromDate: date1, toDate: date2, options: NSCalendarOptions(0))
您必须编写NSCalentarOptions
枚举。