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.
StringI guess? Then, tell me: if you compare: "BBB" and "BBABBB", which one will be "first"? How is the comparison between Strings done? Compare characters at 0, then compare characters at 1, then compare characters at 2, etc. How is aIntcompare? If you compare10and2, is that the same logic? No. Transform the price into a Int or a Double. Maybe use it into your struct too as such.