将代码从swift更改为swift 2.0

时间:2015-07-31 11:31:44

标签: swift swift2

我想将我的swift代码更改为swift 2.0 我希望你能帮助我。

                let calendar = NSCalendar.currentCalendar()
            let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay , fromDate:  notification.fireDate!)
            var gregorian:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
            let unit: NSCalendarUnit = .CalendarUnitHour | .CalendarUnitMinute
            var comps:NSDateComponents = gregorian.components(unit, fromDate: timepicker.date)


            comps.setValue(components.day, forComponent: NSCalendarUnit.CalendarUnitDay)
            comps.setValue(components.month, forComponent: NSCalendarUnit.CalendarUnitMonth)
            comps.setValue(components.year, forComponent: NSCalendarUnit.CalendarUnitYear)
            comps.setValue(comps.hour, forComponent: NSCalendarUnit.CalendarUnitHour)
            comps.setValue(comps.minute, forComponent: NSCalendarUnit.CalendarUnitMinute)
            var NewFiredate : NSDate = gregorian.dateFromComponents(comps)!

在我的代码的这一部分中,我得到以下错误:

  • 找不到会员'CalendarUnitYear'
  • 找不到会员'CalendarUnitHour'
  • 'NSCalendarUnit.Type'没有名为'CalendarUnitHour'的成员
  • 'NSCalendarUnit.Type'没有名为'CalendarUnitMinute'的成员

非常感谢你:)

1 个答案:

答案 0 :(得分:3)

您可以使用下面的代码,基本上我用新的 OptionSetType 语法替换了枚举,并进行了一些小的更改。 NSCalendarUnit OptionSetType具有您可以使用的这些静态类型,

static var Era: NSCalendarUnit { get }
static var Year: NSCalendarUnit { get }
static var Month: NSCalendarUnit { get }
static var Day: NSCalendarUnit { get }
static var Hour: NSCalendarUnit { get }
static var Minute: NSCalendarUnit { get }
static var Second: NSCalendarUnit { get }
static var Weekday: NSCalendarUnit { get }
static var WeekdayOrdinal: NSCalendarUnit { get }
static var Quarter: NSCalendarUnit { get }
static var WeekOfMonth: NSCalendarUnit { get }
static var WeekOfYear: NSCalendarUnit { get }
static var YearForWeekOfYear: NSCalendarUnit { get }
static var Nanosecond: NSCalendarUnit { get }
static var Calendar: NSCalendarUnit { get }
static var TimeZone: NSCalendarUnit { get }

所以,你的新代码看起来像这样,

let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day] , fromDate:  notification.fireDate!)
var gregorian:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let unit: NSCalendarUnit = [.Hour, .Minute]
var comps:NSDateComponents = gregorian.components(unit, fromDate: timepicker.date)


comps.setValue(components.day, forComponent:.Day)
comps.setValue(components.month, forComponent:.Month)
comps.setValue(components.year, forComponent:.Year)
comps.setValue(comps.hour, forComponent:.Hour)
comps.setValue(comps.minute, forComponent:.Minute)
var NewFiredate : NSDate = gregorian.dateFromComponents(comps)!