Swift 3 - Comparing Date objects

后端 未结 14 1537
野的像风
野的像风 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:36

    As of the time of this writing, Swift natively supports comparing Dates with all comparison operators (i.e. <, <=, ==, >=, and >). You can also compare optional Dates but are limited to <, ==, and >. If you need to compare two optional dates using <= or >=, i.e.

    let date1: Date? = ...
    let date2: Date? = ...
    if date1 >= date2 { ... }
    

    You can overload the <= and >=operators to support optionals:

    func <= (lhs: T?, rhs: T?) -> Bool {
        return lhs == rhs || lhs < rhs
    }
    
    func >= (lhs: T?, rhs: T?) -> Bool {
        return lhs == rhs || lhs > rhs
    }
    

提交回复
热议问题