Jonathan Clark
Jonathan Clark

Reputation: 20558

How to get multidimensional array working in tableview

I am creating an iOS Swift 3 app and in this app I have a tableview with data coming from an API. I want to display this data in the tableview but I want to do it grouped by firstname. I have managed to first group the data (see below) but xCode is complaining that XXX.

This is the declaration of the sections:

var sections = [String: [User]]()

This is how I group the data:

self.sections = Dictionary(grouping: self.contacts.filter({ !$0.firstname!.isEmpty })) {
                $0.firstname!.prefix(1).capitalized
            }

This is my output:

["D": [motto.User(id: Optional(1), firstname: Optional("Dan"), lastname: Optional("Meeler"), email: Optional("[email protected]"))], "M": [coiqo.User(id: Optional(3), firstname: Optional("Mia"), lastname: Optional("Kallas"), email: Optional("[email protected]"))]]

This is the error I got:

Cannot subscript a value of type '[String : [User]]' with an index of type 'Int'

In this function for tableview:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].count
    }

How can I get this array to work in a tableview?

Update

I just had to add this to dasblinkenlight answer and it worked!

if(groupKeys.count > 0) {
            return sections[groupKeys[section]]!.count
        } else {
            return sections.count
        }

Upvotes: 2

Views: 67

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

Your self.sections is Dictionary, and dictionaries are unordered.

Once you've made user groups from API results, make a separate array composed of group keys:

let groupKeys : [String] = Array(self.sections.keys)

Sort that array in the way that you wish your sections to appear (alphabetical, reverse alphabetical, natural, etc.)

Now you can write your function like this:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[groupKeys[section]].count
}

Upvotes: 1

Related Questions