Sorting nil Dates to the end of an Array

让人想犯罪 __ 提交于 2019-12-07 01:00:47

问题


Trying to sort an array in Swift in descending order. This works well

objectArray.sort{ $0.date!.compare($1.date!) == .orderedDescending}

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.


回答1:


Maybe not the cleanest solution, but you can do it in one step with nil-coalescing.

objectArray.sort{ ($0.date ?? .distantPast) > ($1.date ?? .distantPast) }


来源:https://stackoverflow.com/questions/44144298/sorting-nil-dates-to-the-end-of-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!