简体   繁体   English

如何比较日期类型的2个操作数? 在Swift中对数组进行排序?

[英]How do you compare 2 operands of type Date? to sort an array in Swift?

In order to sort an array of a custom struct that has bools, integers, and dates. 为了对具有布尔值,整数和日期的自定义结构的数组进行排序。 I successfully used the syntax below for a boolean value and it works for the "bride" and "groom" cases. 我已成功将以下语法用于布尔值,并且适用于“新娘”和“新郎”的情况。 When I attempted to add a sort for 2 Date variables though, I got the error error that: 当我尝试为2个Date变量添加排序时,出现以下错误错误:

"Binary operator '>' cannot be applied to two 'Date?' “二进制运算符'>'不能应用于两个'Date?' operands" 操作数”

I was under the impression that Date values could get compared in a similar fashion with normal > < == criteria, but I presume I am getting the error because the values are not unwrapped? 我的印象是,可以使用与正常的> < ==标准类似的方式比较Date值,但是我想我会收到错误,因为这些值未展开? If that is correct , I don't think I can do an if let to turn Date? 如果是正确的话,我认为我不能做一个“让日期”吗? into an unwrapped Date, so I am not sure how I can compare these values. 转换为未包装的日期,因此我不确定如何比较这些值。

    var sortedImages = [submitted_image]()
    switch sortOption {
    case .brideInPic:
        print("bride")
        sortedImages = Images.sorted(by: {$0.brideInPic && !$1.brideInPic})
        print("sortedImages: \(sortedImages.count), Images: \(Images.count)")
    case .groomInPic:
        print("groom")
        sortedImages = Images.sorted(by: {$0.groomInPic && !$1.groomInPic})
        print("sortedImages: \(sortedImages.count), Images: \(Images.count)")
    case .create_dt:
        print("create")
        sortedImages = Images.sorted(by: {$0.create_dt > $1.create_dt})
    }

Optionals cannot be compared directly (compare SE-0121 – Remove Optional Comparison Operators ). 不能直接比较可选项(比较SE-0121 –删除可选比较运算符 )。 But you can use the nil-coalescing operator ?? 但是您可以使用nil-coalescing运算符?? to provide a default date for entries without creation date: 为没有创建日期的条目提供默认日期:

Images.sorted(by: {$0.create_dt ?? .distantPast > $1.create_dt ?? .distantPast })

With .distantPast the entries without creation date are sorted to the end of the list. 使用.distantPast ,没有创建日期的条目将排序到列表的末尾。 With .distantFuture they would be sorted to the start of the list. 使用.distantFuture它们将被排序到列表的开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM