Swift 3 - Comparing Date objects

后端 未结 14 1557
野的像风
野的像风 2020-11-30 07:14

I\'m updating my app to Swift 3.0 syntax (I know it\'s still in beta but I want to be prepared as soon as it released).

Until the previous Beta of Xcode (Beta 5) I wa

14条回答
  •  余生分开走
    2020-11-30 07:51

    Date is Comparable & Equatable (as of Swift 3)

    This answer complements @Ankit Thakur's answer.

    Since Swift 3 the Date struct (based on the underlying NSDate class) adopts the Comparable and Equatable protocols.

    • Comparable requires that Date implement the operators: <, <=, >, >=.
    • Equatable requires that Date implement the == operator.
    • Equatable allows Date to use the default implementation of the != operator (which is the inverse of the Equatable == operator implementation).

    The following sample code exercises these comparison operators and confirms which comparisons are true with print statements.

    Comparison function

    import Foundation
    
    func describeComparison(date1: Date, date2: Date) -> String {
    
        var descriptionArray: [String] = []
    
        if date1 < date2 {
            descriptionArray.append("date1 < date2")
        }
    
        if date1 <= date2 {
            descriptionArray.append("date1 <= date2")
        }
    
        if date1 > date2 {
            descriptionArray.append("date1 > date2")
        }
    
        if date1 >= date2 {
            descriptionArray.append("date1 >= date2")
        }
    
        if date1 == date2 {
            descriptionArray.append("date1 == date2")
        }
    
        if date1 != date2 {
            descriptionArray.append("date1 != date2")
        }
    
        return descriptionArray.joined(separator: ",  ")
    }
    

    Sample Use

    let now = Date()
    
    describeComparison(date1: now, date2: now.addingTimeInterval(1))
    // date1 < date2,  date1 <= date2,  date1 != date2
    
    describeComparison(date1: now, date2: now.addingTimeInterval(-1))
    // date1 > date2,  date1 >= date2,  date1 != date2
    
    describeComparison(date1: now, date2: now)
    // date1 <= date2,  date1 >= date2,  date1 == date2
    

提交回复
热议问题