Have any Question?

You can ask below or enter what you are looking for!

Group by on Array of custom objects

Presenting a long list of items to user may not be a good decision because you will have the user keep scrolling till he finds what he is looking for, instead you can group these items in sections for ease of navigation.
Dictionary introduce a simple method for grouping objects of array using one of the object’s properties.
Lets start by creating a simple object like this:

class Student {
    
    var name: String?
    var gender: String?
    
    init(name: String, gender: String) {
        self.name = name
        self.gender = gender
    }
}

Now we will create an array of students and group them by gender

        let items = [Student(name: "Jack", gender: "male"), Student(name: "Mike", gender: "male"),
                     Student(name: "Sandy", gender: "female"), Student(name: "Harry", gender: "male"),
                     Student(name: "Magi", gender: "female")]
        
        let groupedItems = Dictionary(grouping: items, by: {$0.gender!})
        
        print(groupedItems)

This is the output of the print statement, the keys are the grouping and the values are arrays of elements for each key

["female": [ios_tutorial.Student, ios_tutorial.Student], "male": [ios_tutorial.Student, ios_tutorial.Student, ios_tutorial.Student]]

Leave a Reply

Your email address will not be published. Required fields are marked *