【发布时间】:2019-06-01 20:38:55
【问题描述】:
我遇到了数组排序问题。
我正在尝试对数组进行排序,但没有得到预期的结果。
如果我想在计数相同时进行排序,它们也会按价格排序。
我的方法有什么问题?
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
})
这是我的排序结果:
[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)]
当计数相同时,我想按价格降序对数组进行排序。
【问题讨论】:
-
价格是
String我猜?那么,告诉我:如果你比较:“BBB”和“BBABBB”,哪个会是“第一”?字符串之间的比较是如何完成的?比较 0 处的字符,然后比较 1 处的字符,然后比较 2 处的字符,等等。Int是如何比较的?如果你比较10和2,是不是同一个逻辑?不,将价格转换为 Int 或 Double。也许也可以在你的结构中使用它。