Home > Software engineering >  iterating through dictionary in TableView
iterating through dictionary in TableView

Time:03-10

this might be a common situation, but I was not able to figure out a way how to do it.

I have a dictionary with the stock amount for several items: dict = ["item1" : 2, "item2" : 5, "item3" : 10 ]

How can I now assign the keys and values to different labels in a tableView, using indexPath?

The logic I want to achieve:

cell.itemLabel.text = dict.[firstItemName]
cell.amountLabel.text = dict.[firstItemAmount]

CodePudding user response:

A dictionary as data source can be annoying because a dictionary is unordered.

My suggestion is to map the dictionary to an array of a custom struct and sort the array by the keys

struct Model {
    let name : String
    let value: Int
}

let dict = ["item1" : 2, "item2" : 5, "item3" : 10 ]

let array = dict.map(Model.init).sorted{$0.name < $1.name}

Then in the table view you can write

cell.itemLabel.text = array[indexPath.row].name

CodePudding user response:

You can use map function to get separate array of key and values

print(dict.map({$0.key}))
print(dict.map({$0. value}))

Try this:

cell.itemLabel.text = dict.map({$0.key})[indexPath.row]
cell.amountLabel.text = dict.map({$0.value})[indexPath.row]
  • Related