我有一个带有根字典和加载字母键的 .plist 文件:

["A": ["AXB", "ACD", "ABC"], ... ]

正确的做法是:
["A": ["ABC", "ACD", "AXB"], ... ]

然后,我想对 A 索引的这个数组的 itens 进行排序。所以,我尝试这样做:
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 的键

ios - 在 Swift 3 字典中对数组值进行排序-LMLPHP

任何帮助将不胜感激。提前致谢!

最佳答案

您只需要对字典键进行排序并将每个排序的值(数组)附加到结果数组 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"

您的最终表格 View 应如下所示:
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
    }
}

关于ios - 在 Swift 3 字典中对数组值进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39502568/

10-12 04:12
查看更多