Yann Massard
Yann Massard

Reputation: 293

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 ...

Upvotes: 0

Views: 654

Answers (2)

J.Wang
J.Wang

Reputation: 1236

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
}

Upvotes: 0

Yann Massard
Yann Massard

Reputation: 293

Sorry for wastin your time, was simple, I was mistaken in the way I was trying to declare an array of array

just had to do

data = [[getitems]]()

Upvotes: 1

Related Questions