[英]Sorting Array values in Dictionary of Swift 3
我有一个.plist文件与根字典和加载字母键如下:
["A": ["AXB", "ACD", "ABC"], ... ]
这是正确的:
["A": ["ABC", "ACD", "AXB"], ... ]
然后,我想排序这个数组的A指数。 所以,我尝试这样做:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var musicalGroups : NSDictionary = NSDictionary()
var keysOfMusicalGroups : NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
let bundle = Bundle.main
let path = bundle.path(forResource: "bandas", ofType: "plist")
musicalGroups = NSDictionary(contentsOfFile: path!)!
keysOfMusicalGroups = NSMutableArray(array: musicalGroups.allKeys)
keysOfMusicalGroups.sort(using: NSSelectorFromString("compare:"))
}
我只使用keysOfMusicalGroups.sort代码对Dictionary进行了排序
任何帮助将不胜感激。 提前致谢!
您只需对字典键进行排序,并将每个值(数组)附加到生成的数组2D中:
let dict = ["A": ["Angra", "Aerosmith", "ACDC", "Avantasia"],"B": ["Barao Vermelho", "Bon Jovi", "Bee Gees"],"C": ["Cachorro Loco", "Coldplay", "Creed"] ]
let sortedArray2D = dict.sorted{ $0.key < $1.key }.map { $0.value.sorted() }
print(sortedArray2D) // "[["ACDC", "Aerosmith", "Angra", "Avantasia"], ["Barao Vermelho", "Bee Gees", "Bon Jovi"], ["Cachorro Loco", "Coldplay", "Creed"]]\n"
您的最终表格视图应如下所示:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var musicalGroups: [[String]] = []
var musicalTitles: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
let dict = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "bandas", ofType: "plist")!) as? [String: [String]] ?? [:]
musicalTitles = dict.keys.sorted()
musicalGroups = dict.sorted{ $0.key < $1.key }.map { $0.value.sorted() }
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return musicalGroups[section].count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return musicalTitles[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return musicalTitles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "exemplo")
cell.textLabel?.text = musicalGroups[indexPath.section][indexPath.row]
return cell
}
}
基于@ Leo-Dabus的更具表现力的答案是:
let dict = ["A": ["Angra", "Aerosmith", "ACDC", "Avantasia"],"B": ["Barao Vermelho", "Bon Jovi", "Bee Gees"],"C": ["Cachorro Loco", "Coldplay", "Creed"] ]
let sortedArray2D: [[String]] = dict.keys.sorted().map{ dict[$0]!.sorted() }
print(sortedArray2D) // "[["ACDC", "Aerosmith", "Angra", "Avantasia"], ["Barao Vermelho", "Bee Gees", "Bon Jovi"], ["Cachorro Loco", "Coldplay", "Creed"]]\n"
这样做效果更好,因为编译器现在知道sortedArray2D
与dict
具有相同的大小。
此外,这种方式sortedArray2D
是一个常量( let
),而不再是var
(允许进一步的性能增强)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.