【问题标题】:Swift 2.0: Cannot convert NSDateComponents to NSCalendarUnitSwift 2.0:无法将 NSDateComponents 转换为 NSCalendarUnit
【发布时间】:2015-11-17 20:56:05
【问题描述】:

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

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

问题代码:

无法将 NSDateComponents 类型的值转换为预期参数 输入 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: [])

【问题讨论】:

  • 如果您希望有人帮助您,您可能需要包含整行代码以及您使用的变量的声明/定义语句。
  • @MartinR 他似乎也为第一个参数传递了错误的类型(除了选项问题)
  • 顺便说一句,如果您打算向最终用户显示此经过的时间,您可以绕过其中的一些内容并直接转到NSDateComponentsFormatter,例如let formatter = NSDateComponentsFormatter(); formatter.unitsStyle = .Full; formatter.allowedUnits = [.Day, .Hour, .Minute]; let string = formatter.stringFromDate(firstDate, toDate: secondDate);

标签: ios swift nscalendar


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多