你如何比较 2 个 Date 类型的操作数?在 Swift 中对数组进行排序? [英] How do you compare 2 operands of type Date? to sort an array in Swift?

查看:37
本文介绍了你如何比较 2 个 Date 类型的操作数?在 Swift 中对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了对具有布尔值、整数和日期的自定义结构数组进行排序.我成功地将下面的语法用于布尔值,它适用于新娘"和新郎"的情况.但是,当我尝试为 2 个 Date 变量添加排序时,出现以下错误:

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:

二元运算符>"不能应用于两个日期?"操作数"

"Binary operator '>' cannot be applied to two 'Date?' operands"

我的印象是日期值可以与普通<代码>>以类似的方式进行比较.<== 标准,但我认为我收到错误是因为值没有被解包?如果那是正确的,我不认为我可以做一个 if let to turn Date?进入一个未包装的日期,所以我不确定如何比较这些值.

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? 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 不能直接比较(比较 SE-0121 – 删除可选的比较运算符).但是您可以使用 nil-coalescing 运算符 ?? 为没有创建日期的条目提供默认日期:

Optionals cannot be compared directly (compare SE-0121 – Remove Optional Comparison Operators). But you can use the nil-coalescing operator ?? to provide a default date for entries without creation date:

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

使用 .distantPast 条目没有创建日期的被排序到列表的末尾.使用 .distantFuture 他们将被排序为列表的开头.

With .distantPast the entries without creation date are sorted to the end of the list. With .distantFuture they would be sorted to the start of the list.

这篇关于你如何比较 2 个 Date 类型的操作数?在 Swift 中对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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