【问题标题】:Swift sort dictionary for table view表视图的 Swift 排序字典
【发布时间】:2016-05-14 15:50:18
【问题描述】:

我有一本用于填充表格的字典:

["struvite":716,"calcium_oxalate":388,"urate":217,"calcium_phosphate":30,"silica":21,"compound":41]

我了解字典根据定义是未排序的,并且 tableView 适用于数组,而不是字典。

所以我的问题有两个。我需要按值对这些数据进行排序并将其放在一个数组中,以便我可以轻松地将其放入表中。我发现这个answer 用于排序,但对于 Swift 2 来说似乎已经过时了。

我正在寻找的结果是这样的:


鸟粪石 (716)

草酸钙 (388)

尿酸盐 (217)

复合 (41)

磷酸钙 (30)

二氧化硅 (21)


其中每一行都是数组的一个元素,它们按照它们曾经在字典中的值以降序出现。一旦它在一个数组中,我就可以把它放到一个表中。

【问题讨论】:

    标签: ios swift uitableview dictionary


    【解决方案1】:
    let dict = ["struvite": 716, "calcium_oxalate": 388, "urate": 217, "calcium_phosphate": 30, "silica": 21, "compound": 41]
    let test = dict.sort { $0.1 > $1.1 }
    

    结果是:

    [("struvite", 716), ("calcium_oxalate", 388), ("urate", 217), ("compound", 41), ("calcium_phosphate", 30), ("silica", 21)]
    

    您可以像这样访问它并将其分配给您的单元格:

    let name = test[indexPath.row].0
    let number = test[indexPath.row].1
    

    【讨论】:

    • 完美。我的错误在于认为因为字典没有排序,所以我无法在字典上调用 sort。
    【解决方案2】:

    如果dictionary : [String:Int].

    struct Compound : Equatable, Comparable {
       let name : String
       let value : Int
    }
    func ==(x : Compound, y : Compound) -> Bool {
       return x.value == y.value
    }
    func <(x : Compound, y : Compound) -> Bool {
       return x.value < y.value
    }
    
    var compounds = [Compound]()
    for (key, value) in dictionary {
       compounds.append(Compound(name: key, value: value)
    }
    let sorted = compounds.sort(>)
    

    【讨论】:

      【解决方案3】:

      从你的例子开始:

      let dict = ["struvite":716,"calcium_oxalate":388,"urate":217,"calcium_phosphate":30,"silica":21,"compound":41]
      

      这部分将从最大的排序并实际将字典转换为元组数组:

      let sortedTupples = dict.sort { (lhs, rhs) -> Bool in
          return lhs.1 > rhs.1
      }
      

      这将得到您想要的确切形式,它是一个字符串数组:

      let arrayOfStringsFromTupples = sortedTupples.map { "\($0.0) (\($0.1))" }
      

      Map 函数将每个元组条目映射到 clojure 类型中定义的,这里我们只是在字符串对象上创建,但实际上它可以是任何不同的对象。

      简而言之

      let dict = ["struvite":716,"calcium_oxalate":388,"urate":217,"calcium_phosphate":30,"silica":21,"compound":41]
      let allInOne = dict.sort { (lhs, rhs) -> Bool in
          return lhs.1 > rhs.1
      }.map { "\($0.0) (\($0.1))" }
      

      【讨论】:

        猜你喜欢
        • 2016-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-22
        • 2016-11-19
        • 2016-09-14
        • 1970-01-01
        • 2011-09-23
        相关资源
        最近更新 更多