ios - swift数组排序结果问题

标签 ios arrays swift sorting

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

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/

相关文章:

ios - Swift:我应该为 Firebase 管理器类使用静态成员吗​​?好的程序设计

ios - 将视频转换为mp4格式

PHP 'foreach' 数组连接回显

enums - 使用 Xcode 6.1 的 Swift 枚举 .toRaw 和 .fromRaw

ios - 在 Swift 中重试 firebase token

ios - 在 UIView 中定位文本

android - 适用于 Android/iOS 的 WMS View /库

c - 如何创建未定义大小的数组?

javascript - 从数组中的对象添加值

swift - 想快速创建一个像谷歌这样的搜索栏