簡體   English   中英

用於表視圖的Swift排序字典

[英]Swift sort dictionary for table view

我有一本字典,將用於填充表格:

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

我知道,按照定義,字典是不排序的,並且tableView可以在數組上工作,而不是字典。

所以我的問題是兩個方面。 我需要按值對這些數據進行排序並將其放置在數組中,以便可以輕松地將其放入表中。 我找到了這個答案進行排序,但是對於Swift 2來說似乎已經過時了。

我正在尋找的結果將是這樣的:


鳥糞石(716)

草酸鈣(388)

尿酸鹽(217)

化合物(41)

磷酸鈣(30)

二氧化硅(21)


其中每一行都是數組的元素,它們按照在字典中曾經是它們的值的降序出現。 將其放入數組后,可以將其放入表中。

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

快速實現此目的的簡便方法是按照以下方式進行操作,假設使用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(>)

從您的示例開始:

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函數將每個tupple條目映射為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))" }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM