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

标签 ios arrays swift sorting

为了对包含 bool 值、整数和日期的自定义结构数组进行排序。我成功地将下面的语法用于 bool 值,它适用于“新娘”和“新郎”的情况。当我尝试为 2 个日期变量添加排序时,我收到以下错误:

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

我的印象是,日期值可以以与正常 > < == 类似的方式进行比较。 标准,但我认为我收到错误是因为这些值未解开?如果这是正确的,我不认为我可以做一个 if let 来转动日期?到一个展开的日期中,所以我不确定如何比较这些值。

    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})
    }

最佳答案

选项不能直接比较(比较 SE-0121 – Remove Optional Comparison Operators )。但是您可以使用零合并运算符 ?? 为没有创建日期的条目提供默认日期:

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

.distantPast没有创建日期的条目将排序到列表的末尾。与.distantFuture它们将被排序到列表的开头。

关于ios - 如何比较两个日期类型的操作数?在 Swift 中对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56364854/

相关文章:

iphone - NSString 到 NSURL?

ios - 动画 TableView 单元格以向左滑动

python - 为什么对列表的操作比对 numpy 数组的操作慢

python - 如何使用 pygame 将整个像素数组放在屏幕上?

c++ - 传递给函数时限制数组的大小

ios - 为什么我的代码没有向键盘添加工具栏和完成按钮?

ios - 如何使用 DeviceCheck.DCDevice Xamarin Forms C# 生成 token 代码 iOS DeviceId

swift - 无法转换类型 'NSAttributedString.DocumentAttributeKey' 的值, "DocumentReadingOptionKey"也不起作用

swift - 编译器不将私有(private)扩展中的方法识别为私有(private)

ios - 我如何将这四行代码从 AVAudioPlayer 转换为 AVPlayer?