Joe
Joe

Reputation: 3911

Displaying dictionary values each in a UITableViewCell

My overall objective here is to create a UITableView that has alphabetical section titles based on the values in a dictionary.

I have a basic object which includes the fruit's name and description. I would like the names of the fruit to each be displayed on a UITableCell, under the cooresponding letter for the section title.

Ultimately, the tableview will look something like this: (where C P S are the section titles)

C------------
Clementine
Cherry
Coconut
P------------
Pear
Peach
S------------
Strawberry

Here is my data:

var fruitModel = [String:Any]()


fruitModel = [
    "C" : [
    FruitModel(name: "Clementine", description: "Clementines are super tasty!"),
    FruitModel(name: "Cherry", description: "Cherry's are red."),
    FruitModel(name: "Coconut", description: "Nuts for coconuts!!!"),
    ],
    "P" : [
    FruitModel(name: "Pear", description: "Pears rock!"),
    FruitModel(name: "Peach", description: "Mmmm, Peach."),
    ],
    "S" : [
    FruitModel(name: "Strawberry", description: "A widely grown hybrid species of the genus Fragaria. It is cultivated worldwide for its fruit.")
    ]
]

The part that's throwing me off is accessing the name string, inside the dictionary's value, and displaying it in cellForRowAt. The code below is where I am stuck:

cellForRowAt:

var allValues = Array(fruitModel.values)
cell.fruitNameLabel.text = (allValues[indexPath.row] as AnyObject).name // Cannot subscript a value of type 'inout Array<Any>'

Once I figure out how to display the fruit names in each cell, I'll be able to get the section titles working. I just need assistance with my error that i'm getting. Thanks.

Upvotes: 1

Views: 2872

Answers (3)

Karan Champaneri
Karan Champaneri

Reputation: 915

here full example for your query

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

struct FruitModel {
    var name: String
    var description: String
}
var fruitModel = [String: [FruitModel]]()
var dataKeys : Array = [String]()


@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    tableView.delegate = self
    tableView.dataSource = self
    fruitModel = [
        "C" : [
        FruitModel(name: "Clementine", description: "Clementines are super tasty!"),
        FruitModel(name: "Cherry", description: "Cherry's are red."),
        FruitModel(name: "Coconut", description: "Nuts for coconuts!!!"),
        ],
        "P" : [
        FruitModel(name: "Pear", description: "Pears rock!"),
        FruitModel(name: "Peach", description: "Mmmm, Peach."),
        ],
        "S" : [
        FruitModel(name: "Strawberry", description: "A widely grown hybrid species of the genus Fragaria. It is cultivated worldwide for its fruit.")
        ]
    ]

    dataKeys = (fruitModel as NSDictionary).allKeys as! [String]
    print(dataKeys)
    tableView.reloadData()

}

func numberOfSections(in tableView: UITableView) -> Int {
    return dataKeys.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let sec = dataKeys[section]
    return fruitModel[sec]?.count ?? 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return dataKeys[section]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    let sec = dataKeys[indexPath.section]
    cell.textLabel?.text = fruitModel[sec]?[indexPath.row].name

    return cell;
}
}

Upvotes: 0

Srinivasan_iOS
Srinivasan_iOS

Reputation: 1088

Display for Array of dictionary values in table view in swift

var arrayDictionary = [[String:Any]]()


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cellTable = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
            cellTable.labelTitle.text = arrayDictionary[indexPath.row]["name"] as? String
            cellTable.labelAuthor.text = arrayDictionary[indexPath.row]["region"] as? String
            cellTable.labelDescription.text = arrayDictionary[indexPath.row]["subregion"] as? String
            return cellTable
        }

Upvotes: 0

Darryl Johnson
Darryl Johnson

Reputation: 431

See Swift Dictionary: Get values as array for the error you are facing about the indexing.

However, there is a bigger problem you will face about the order of the cells since dictionary values are not guaranteed to be returned in the order in which they are added.

A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering.

So you will need to rethink the data structure you are using if you want them to be shown alphabetically.

Upvotes: 1

Related Questions