【问题标题】:Problem of result about swift array sorted关于快速数组排序的结果问题
【发布时间】: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 是如何比较的?如果你比较102,是不是同一个逻辑?不,将价格转换为 Int 或 Double。也许也可以在你的结构中使用它。

标签: ios arrays swift sorting


【解决方案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 }

【讨论】:

    【解决方案2】:

    可能你想让你的price在你的结构或类中变成IntDoubleString比较只比较第一个字符,所以“8814388”>“12100396”,这个转换应该有效:

    self.array = items.sorted(by: { ($0.count >= $1.count) && (Double($0.price) ?? 0 > Double($1.price) ?? 0) })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-31
      • 2018-03-14
      • 1970-01-01
      • 2019-04-21
      • 2018-02-20
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      相关资源
      最近更新 更多