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

这一生的挚爱 提交于 2019-11-28 13:04:36

问题


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


来源:https://stackoverflow.com/questions/46630192/error-binary-operator-cannot-be-applied-to-operands-of-type-int-and-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!