我遇到了数组排序的问题。
我正在尝试对数组进行排序,但没有得到预期的结果。
如果我想在数量相同时排序,它们也会按价格排序。
我的方法有什么问题吗?
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)]
当计数相同时,我想按价格降序对数组进行排序。
最佳答案
词法上 10
大于 2
,但 "10"
小于 "2"
有 API 可以按数字方式对字符串进行排序
self.array = items.sorted { ($0.count >= $0.count) && $0.price.compare($1.price, options: .numeric) == .orderedAscending }
或
self.array = items.sorted { ($0.count >= $0.count) && $0.price.localizedStandardCompare($1.price) == .orderedAscending }
关于ios - swift数组排序结果问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070025/