快速数组排序结果的问题

快速数组排序结果的问题

本文介绍了快速数组排序结果的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到数组排序问题.
我正在尝试对数组进行排序,但是没有得到预期的结果.如果我想在计数相同时进行排序,它们也会按价格进行排序.
我的方法有什么问题?

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
             })

这是我的排序结果:

[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.

推荐答案

可能您想使price成为结构或类中的IntDoubleString比较仅比较第一个字符因此"8814388">"12100396",此转换应有效:

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) })

这篇关于快速数组排序结果的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 20:34