Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift numberOfRowsInSection from dictionary

Hello everybody this is my first post. I'm trying to show dynamic data in a TableView: I have the data in a Dictionary like this var dizionarioComuni : Dictionary<Character, Array<ComuneModel>> = [:] The object ComuneModel is a custom model whit data as nomeComune, numAbitanti and so on In the TableView i wrote this code to obtain the numbers of the sections and it works

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    //tot valori nel dictionary
    dizionarioComuni.count
}

The keys of the dictionary are Charachters because i want use these keys as title of the section. The question is: how can i get the numberOfRowsInSection in the method of the table view ? the signature of the method is this

 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

anf take an integer but my keys are charachters. I try to access to all the keys of the dictionary with this code

var keys = dizionarioComuni.keys

I can iterate over the keys but then how can i access from a specific key at the object list (of ComuniModel) at a specific index (the section: Int) that is the parameter of the method?

i search for similar question but the answer doesn't talk about this case. thanks a lot

like image 278
Sandro Avatar asked Jun 15 '26 11:06

Sandro


1 Answers

Swift dictionaries are unordered, so you need to maintain a separate list of sorted keys and use that to access your data.

var sortedKeys = dizionarioComuni.keys.sort()

Then numberOfRowsInSection becomes:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dizionarioComuni[sortedKeys[section]]?.count ?? 0
}

Note: any time your list of keys changes, you will need to reload the data in your table.


class MyTableViewController: UITableViewController {
    var sortedKeys = [Character]() {
        didSet {
            if oldValue != sortedKeys {
                // reload tableView
                tableView.reloadData()
            }
        }
    }
    var dizionarioComuni = [Character: [ComuneModel]]() {
        didSet {
            sortedKeys = dizionarioComuni.keys.sort()
        }
    }
}
like image 173
vacawama Avatar answered Jun 18 '26 00:06

vacawama