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