Error: Binary operator '<=' cannot be applied to operands of type 'Int?' and 'Int'

Error: Binary operator '<=' cannot be applied to operands of type 'Int?' and '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?。这意味着它们可以包含零。

因此,您无法直接将日期组件与非可选值进行比较。你必须"unwrap"他们。

如果您 100% 确定总会有一个 .second 组件,您可以通过添加感叹号来强制展开该值:

if differenceOfDate.second! <= 0