Swift 2.0 calendar components error

廉价感情. 提交于 2019-11-26 05:35:56

问题


Hi I get this error in swift 2.0

Cannot invoke \'components\' with an argument list of type \'(NSCalendarUnit, fromDate: NSDate?, toDate: NSDate?, options: nil)\'

var hoy = dataFormatter.stringFromDate(NSDate())
        var despues = dataFormatter.stringFromDate(fecha)
        var calHoy = dataFormatter.dateFromString(hoy)
        var calcDesp = dataFormatter.dateFromString(despues)
        let cal = NSCalendar.currentCalendar()
        let unit:NSCalendarUnit = .Day
        let components = cal.components(unit, fromDate: calcDesp, toDate: calHoy, options: nil) 

回答1:


As of Swift 2, NS_OPTIONS (such as NSCalendarOptions) are mapped to Swift as a OptionSetType which offers a set-like interface. In particular, "no options" can now be specified as [] instead of nil:

let components = cal.components(unit, fromDate: calcDesp!, toDate: calHoy!,
                               options: []) 

See also Swift 2.0 - Binary Operator "|" cannot be applied to two UIUserNotificationType operands and the recently added answers to How to create NS_OPTIONS-style bitmask enumerations in Swift? for more information.




回答2:


You can't pass nil as your options argument. Use an empty option set instead:

let components = cal.components(unit, fromDate: calcDesp!, toDate: calHoy!, options: [])

You also have to make sure to unwrap calcDesp and calHoy.




回答3:


you can also use rawValue like the following :

cal.components(unit, fromDate: calcDesp!, toDate: calHoy!, options: NSCalendarOptions(rawValue: 0))



来源:https://stackoverflow.com/questions/30769387/swift-2-0-calendar-components-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!