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