Search code examples
iosswiftcollectionview

Swift Collectionview Sections from a single array


I have an array of IDs ["one", "two", "three"...]

These Ids are matched against a json I get from a URLSession and then displayed in a collectionview. At the moment it's just one simple collectionView with the feature to reorder it by long press and drag. But I need the possibilty to split it up in sections.

The best thing would be to make the sections dynamic, so that I can add as many sections as I want and then sort the cells into the sections. I get what I could do if I had an array for every section like

section1 = ["one", "two"]

section2 = ["three", "four"]

But I have no Idea how to realize this in my current setup.


Solution

  • Don't do it. I'm sure you could figure out a way to keep the single array, but don't. The maintenance nightmare will haunt you.

    Create a view of the data which is broken into an array of arrays.

    struct MySection {
        let sectionId: String // or whatever section metadata you need.
        let data: [Data] // or whatever your real type is.
    }
    

    In the collection view controller

    var dataView: [MySection]
    

    All the data in 1 section

    self.dataView = [MySection(sectionId: "all data", data: self.data)]
    

    Grouping the data into different sections

    self.dataView = self.data.reduce([]) { dataView, datum in
        var dataView = dataView // make a mutable data view
    
        let sectionId = self.determineSectionIdFromDatum(datum) // <-- slotting into sections
    
        // Add into an existing section or into a new section
        if let index = dataView.index(where: { $0.sectionId == sectionId }) {
            let data = dataView[index].data + [datum]
            dataView[index] = MySection(sectionId: sectionId, data: data)
        } else {
            let data = [datum]
            dataView.append(MySection(sectionId: sectionId, data: data))
        }
    
        return dataView
    }
    

    At this point you will likely need to sort either the sections or the data within the sections.