0

I have an UITableView with a grouped style.

I want to populate this table from an array of objects. Let's say

class User {
   var name : String!
   var age : Int!
   var group : String!
}

User with same group values must be in the same section of my UITableView. To do that, I planed to transform my array to a dictionary with the group as key and an array of the corresponding objects in value but the UITableView request the value via IndexPath and I did't find an easy way to get an hash value by index.

How could I resolve this problem in an elegant way ?

2 Answers 2

1

Typically you would create an array of dictionaries, each dictionary would have the group name and an array of members.

Another alternative is to build your dictionary of groups, just as you are, and then pull the keys into an array and use that array as your group names:

let groupNames = tableData.keys.sort()

Save the group names as a property on the VC and then you can use them to get back to the correct group when you need the user data:

let user = tableData[groupNames[indexPath.section]][indexPath.row]
Sign up to request clarification or add additional context in comments.

Comments

1

You could sort your array according to the group property, and then count how many object you have in each group, and how many groups you have. You could then use the number of groups as the number of sections in the table, and the number of objects for each group as the number of rows in each section.

However, as far as efficiency goes, your solution is pretty decent already, and quite clear. Save for the redundancy of the group information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.