将nil日期排序到数组的末尾 [英] Sorting nil Dates to the end of an Array
本文介绍了将nil日期排序到数组的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试在Swift中按降序对数组进行排序.效果很好
Trying to sort an array in Swift in descending order. This works well
objectArray.sort{ $0.date!.compare($1.date!) == .orderedDescending}
如您所见,我强行解开日期.我正在寻找另一种方法,以便如果日期为nil
,则对象将移动到数组的末尾.
As you can see, I'm force unwrapping the date. I'm looking for another way so that if the date is nil
, the object moves to the end of array.
推荐答案
也许不是最干净的解决方案,但您可以通过零成本一步一步完成.
Maybe not the cleanest solution, but you can do it in one step with nil-coalescing.
objectArray.sort{ ($0.date ?? .distantPast) > ($1.date ?? .distantPast) }
这篇关于将nil日期排序到数组的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文