Error: Binary operator '<=' cannot be a

2020-02-16 05:22发布

问题:

I am getting a error named:

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

on line: if differenceOfDate.second <= 0 Can someone please help!

    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."
    }

回答1:

The documentation you need to look into is the one about the "DateComponents" data type, and if you're not familiar with optionals you need to read up on optionals as well.

In a nutshell, the DateComponents data type may not always contain a value for all the components so each member is an optional Int?. This means that they could contain nil.

Because of this you cannot directly compare the date components with a non-optional value. You have to "unwrap" them.

If you are 100% certain that there will always be a .second component, you can force unwrap the value by adding an exclamation point:

if differenceOfDate.second! <= 0