【发布时间】:2019-04-10 19:16:08
【问题描述】:
我需要知道两个日期之间有多少天,所以我使用了我在网上找到的这段代码
extension Date {
func years(_ sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.year], from: sinceDate, to: self).year
}
func months(_ sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.month], from: sinceDate, to: self).month
}
func days(_ sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.day], from: sinceDate, to: self).day
}
func hours(_ sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.hour], from: sinceDate, to: self).hour
}
func minutes(_ sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.minute], from: sinceDate, to: self).minute
}
func seconds(_ sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.second], from: sinceDate, to: self).second
}
}
这是 Date 类的扩展。
我在使用这些功能时遇到问题,我有这个功能
func countDays() {
if let daysLeft = Date.days(targetDate) {
self.daysLeft = daysLeft
}
}
但 Xcode 告诉我
条件绑定的初始化器必须是 Optional 类型,而不是 '(Date) -> Int?'
所以,然后我尝试了这个功能
func countDays() {
let daysLeft = Date.days(targetDate)
self.daysLeft = daysLeft
}
Xcode 仍然告诉我
无法分配类型“(日期)-> Int?”的值输入'Int'
我已尝试构建该项目几次,因为我认为这可能是一个错误,但问题仍然存在。
谁能指出这可能是什么问题?提前致谢!
编辑:我已经尝试像这样强制解开返回的值
func years(_ sinceDate: Date) -> Int {
return Calendar.current.dateComponents([.year], from: sinceDate, to: self).year!
}
Xcode 仍然告诉我同样的事情 无法将类型 '(Date) -> Int' 的值赋给类型 'Int'
【问题讨论】:
-
与您的问题无关,但您为什么不简单地强制打开结果?每个日期都有年份部分。它永远不会失败。
-
func years(_ sinceDate: Date) -> Int {return Calendar.current.dateComponents([.year], from: sinceDate, to: self).year!} -
let years = Date().years(since: targetDate) -
试试
extension Date { static func days(since date: Date) -> Int { return Calendar.current.dateComponents([.day], from: date, to: Date()).day! } } Date.days(since: targetDate) -
请注意,在这种情况下,我不建议将您的方法声明为静态。我会将其保留为实例方法。我实际上会使用计算属性
extension Date { var daysSinceNow: Int { return Calendar.current.dateComponents([.day], from: Date(), to: self).day! } } Calendar.current.date(byAdding: DateComponents(day: -2), to: Date())!.daysSinceNow // -2