Problem of result about swift array sorted

跟風遠走 提交于 2020-01-16 19:11:32

问题


I am facing a problem with array sorting.
I am trying to sort an array, but not getting the result as expected. If I want to sort when the count are the same, they also get sorted by price.
What's wrong with my approach?

self.array = items.sorted(by: { (item1, item2) -> Bool in 
                 if item1.count > item2.count {                      
                    return true                  
                 } else {                      
                    if item1.count == item2.count {
                        if item1.price > item2.price {
                            return true
                        }
                    }
                 }              
                return false
             })

this is my sort result:

[Item(name: "AAA", count: 7, price: "30737517", index: 0), 
 Item(name: "EEE", count: 3, price: "8814388", index: 4), 
 Item(name: "CCC", count: 3, price: "12100396", index: 2), 
 Item(name: "DDD", count: 1, price: "9403300", index: 3), 
 Item(name: "FFF", count: 1, price: "5072755", index: 5), 
 Item(name: "BBB", count: 1, price: "21477775", index: 1)]

When the count numbers are same, I want to sort the array by price in descending order.


回答1:


Probably you would want to make your price become Int or Double in your struct or class, String comparison only compare the first character so "8814388" > "12100396", this conversion should work:

self.array = items.sorted(by: { ($0.count >= $1.count) && (Double($0.price) ?? 0 > Double($1.price) ?? 0) })



回答2:


Lexically is 10 greater than 2 but "10" is less than "2"

There are APIs to sort strings numerically

self.array = items.sorted { ($0.count >= $0.count) && $0.price.compare($1.price, options: .numeric) == .orderedAscending }

or

self.array = items.sorted { ($0.count >= $0.count) && $0.price.localizedStandardCompare($1.price) == .orderedAscending }


来源:https://stackoverflow.com/questions/54070025/problem-of-result-about-swift-array-sorted

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