问题
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