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

查看:116
本文介绍了如何比较日期类型的2个操作数?在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"

我的印象是,可以使用类似的方式将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 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个操作数?在Swift中对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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