首页 > 解决方案 > Tableview is not sorting once number is above 10

问题描述

I'm sorting tableview using this code:

list.sort() { $0.points > $1.points }

And everything works fine (For a bit) If I use this sort method it's sorting numbers (aka points) all the way up to 10. But once a number is above 10, the list is not getting sorted anymore. And I've no idea how to solve this issue.

Result under 10:

1

Result above 10:

2

I guess it's being placed where it is because of "10", if I would use like "60" it would be placed under the 2nd or 3rd spot. So, how can I solve this? I would be very thankful for it.

标签: iosswifttableview

解决方案


That's the normal behavior when comparing strings. Strings are not numbers.

The method localizedStandardCompare compares like in Finder and handles numeric strings correctly

list.sort() { $0.points.localizedStandardCompare($1.points) == .orderedDescending }

Alternatively compare with .numeric option

list.sort() { $0.points.compare($1.points, options: .numeric) == .orderedDescending }

推荐阅读