Swift 2.0:无法将 NSDateComponents 转换为 NSCalendarUnit

Swift 2.0: Cannot convert NSDateComponents to NSCalendarUnit

这是接收问题代码的代码行:

let CompetitionDayDifference = userCalendar.components (dayCalendarUnit, fromDate: currentDate!, toDate: competitionDay, options: nil)

问题代码:

Cannot convert value of type NSDateComponents to expected argument type NSCalendarUnit

附加代码:

let userCalendar = NSCalendar.currentCalendar()


let competitionDate = NSDateComponents()
competitionDate.year = 2015
competitionDate.month = 6
competitionDate.day = 21
competitionDate.hour = 08
competitionDate.minute = 00
let competitionDay = userCalendar.dateFromComponents(competitionDate)!


// Here we compare the two dates
competitionDay.timeIntervalSinceDate(currentDate!)


let dayCalendarUnit = calendar.components([NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: date)

//here we change the seconds to hours,minutes and days
let CompetitionDayDifference = userCalendar.components (dayCalendarUnit, fromDate: currentDate!, toDate: competitionDay, options: [])

根据错误,您的 dayCalendarUnit 是 NSDateComponents 类型的变量。你应该传递一个 NSCalendarUnit 来代替。从 Swift 2.0 开始,您也不能为选项参数传递 nil,因此您需要传递一个空选项集:

let CompetitionDayDifference = userCalendar.components(NSCalendarUnit.Day, fromDate: currentDate!, toDate: competitionDay, options: [])