我收到一个名为的错误:
二元运算符'< ='不能应用于'Int?'类型的操作数和'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."
}
答案 0 :(得分:1)
您需要查看的文档是关于“DateComponents”数据类型的文档,如果您不熟悉选项,则还需要阅读选项。
简而言之,DateComponents数据类型可能并不总是包含所有组件的值,因此每个成员都是可选的Int?。这意味着它们可以包含零。
因此,您无法直接将日期组件与非可选值进行比较。你必须“打开”它们。
如果您100%确定始终存在.second组件,则可以通过添加感叹号来强制打开该值:
if differenceOfDate.second! <= 0