错误:二元运算符“<="不能应用于“Int?"类型的操作数和“诠释" [英] Error: Binary operator '<=' cannot be applied to operands of type 'Int?' and 'Int'

查看:29
本文介绍了错误:二元运算符“<="不能应用于“Int?"类型的操作数和“诠释"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个错误,名为:

I am getting a error named:

二元运算符<="不能应用于Int?"类型的操作数和诠释"

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

在线:if differenceOfDate.second <= 0 有人可以帮忙吗!

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

推荐答案

您需要查看的文档是关于DateComponents"数据类型的文档,如果您不熟悉可选选项,则需要阅读选项也是如此.

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.

简而言之,DateComponents 数据类型可能并不总是包含所有组件的值,因此每个成员都是可选的 Int?.这意味着它们可以包含 nil.

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.

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

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

这篇关于错误:二元运算符“&lt;="不能应用于“Int?"类型的操作数和“诠释"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆