Search code examples
arraysswiftuitableviewstructsections

Struct and array to populate sections of Tableview in SWIFT


I have a struct (getItems) that defines a post when I read my posts, I store them in an array like so :

var posts = [getItems]()

problem is : I ve decided to create sections in my tableview How can I create an array of posts ? I ve tried to declare var items = [posts]() but this doesn t work

I also have a item counter that counts how many items should be in each section, but I can't figure out how to split my array of getItems into something like :

[index1 : [getItems1, getItems2 ...], index2:[getItems1, getItems2 ...]...]

this so I could call sections and row in my TableView

Sincerely PS : I didn't post any code since it's a lot of data here ...


Solution

  • I'm not entirely sure if this is want you want. Let's say if you have a counter function that will take an section index as parameter and return how many posts should be in this particular section.

    func counter(index: Int) -> Int {
        return index
    }
    

    Then calculate your subarrays like this:

    var currentIndex = 0
    var totalCount = 0
    var sections: [Int: [getitems]] = [:]
    while totalCount < posts.count {
        let currentCounter = counter(currentIndex)
        sections[currentIndex] = posts.suffixFrom(totalCount).prefix(currentCounter).flatMap { $0 }
        currentIndex++
        totalCount += currentCounter
    }
    

    And then in your func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

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