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

前端 未结 1 363
执念已碎
执念已碎 2020-12-22 13:15

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

相关标签:
1条回答
  • 2020-12-22 13:31

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

    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.

    0 讨论(0)
提交回复
热议问题