2017-10-08 68 views
-2

我得到了一個名爲錯誤:錯誤:二進制運算符'<='不能應用於'Int?'類型的操作數和 '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." 
    } 
+1

請查找了資料https://developer.apple .com/documentation/foundation/calendar/2292887-datecomponents,你會發現它使用'Date'類型的參數,而不是'NSDate'。 –

+0

相關:https://stackoverflow.com/questions/41198803/how-to-convert-from-nsdatetimeintervalsince1970-to-nsdate。 –

+0

如果我使用Date來比錯誤「Binary operator'<='不能應用於類型'Int?'的操作數和'Int'「on line'if differenceOfDate.second <= 0' – Danjhi

回答

0

你需要考慮的文檔是關於「DateComponents」數據類型之一,如果你不熟悉自選您需要在自選閱讀起來爲好。

簡而言之,DateComponents數據類型可能並不總是包含所有組件的值,因此每個成員都是可選的Int ?.這意味着它們可以包含零。

因此,您無法直接將日期組件與非可選值進行比較。你必須「打開」它們。

如果你是100%肯定,總是會有一個。第二個組件,您可以強制通過添加一個感嘆號解開值:

if differenceOfDate.second! <= 0 
相關問題