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
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()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With