简体   繁体   中英

Sorting Array values in Dictionary of Swift 3

I have a .plist file with root dictionary and loading keys of letters as:

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

It would be right by:

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

Then, I wanna sort this array's itens of the A index. So, I tried do thus:

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:"))

}

And I got just the keys of Dictionary sorted using keysOfMusicalGroups.sort code

在此输入图像描述

Any help will be appreciated. Thanks in advance!

You just have to sort your dictionary keys and append each value (array) sorted to the resulting array 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"

Your final table view should look like this:

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
    }
}

A more performance-wise answer, based on @Leo-Dabus 's, is:

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"

This performs better because the compiler now knows that sortedArray2D has the same size as dict .

Also, this way sortedArray2D is a constant ( let ), and not a var anymore (allowing even further performance enhancements).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM