错误:二进制运算符'<='不能应用于'Int?'类型的操作数和 'INT'
问题描述:
我得到了一个名为错误:错误:二进制运算符'<='不能应用于'Int?'类型的操作数和 'INT'
Binary operator '<=' cannot be applied to operands of type 'Int?' and 'Int'
在线:if differenceOfDate.second <= 0
能有人请帮助!
let fromDate = Date(timeIntervalSince1970: TimeInterval(truncating: posts[indexPath.row].postDate))
let toDate = Date()
var calendar = Calendar.current
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth, .month])
let differenceOfDate = Calendar.current.dateComponents(components, from: fromDate, to: toDate)
if differenceOfDate.second <= 0 {
cell.DateLbl.text = "now"
}else if differenceOfDate.second > 0 && differenceOfDate.minute == 0 {
cell.DateLbl.text = "\(differenceOfDate.second)s."
}
else if differenceOfDate.minute > 0 && differenceOfDate.hour == 0 {
cell.DateLbl.text = "\(differenceOfDate.minute)m."
}
else if differenceOfDate.hour > 0 && differenceOfDate.day == 0 {
cell.DateLbl.text = "\(differenceOfDate.hour)h."
}
else if differenceOfDate.day > 0 && differenceOfDate.weekOfMonth == 0 {
cell.DateLbl.text = "\(differenceOfDate.day)d."
}
else if differenceOfDate.weekOfMonth > 0 && differenceOfDate.month == 0 {
cell.DateLbl.text = "\(differenceOfDate.weekOfMonth)w."
}
else if differenceOfDate.month > 0 {
cell.DateLbl.text = "\(differenceOfDate.month)m."
}
答
你需要考虑的文档是关于“DateComponents”数据类型之一,如果你不熟悉自选您需要在自选阅读起来为好。
简而言之,DateComponents数据类型可能并不总是包含所有组件的值,因此每个成员都是可选的Int ?.这意味着它们可以包含零。
因此,您无法直接将日期组件与非可选值进行比较。你必须“打开”它们。
如果你是100%肯定,总是会有一个。第二个组件,您可以强制通过添加一个感叹号解开值:
if differenceOfDate.second! <= 0
请查找了资料https://developer.apple .com/documentation/foundation/calendar/2292887-datecomponents,你会发现它使用'Date'类型的参数,而不是'NSDate'。 –
相关:https://stackoverflow.com/questions/41198803/how-to-convert-from-nsdatetimeintervalsince1970-to-nsdate。 –
如果我使用Date来比错误“Binary operator' Danjhi