Reputation: 7012
I would like to populate a tableView.
My data is inside an array
var myDataArray = [DataEntry]()
The DataEntry
-type is a protocol such as:
protocol DataEntry: class {
var idx: Int { get set }
var category: String { get set }
var title: String { get set }
}
The order of my data-array is such as:
idx=0: category = "Section0" / title = "Row0"
idx=1: category = "Section0" / title = "Row1"
idx=2: category = "Section0" / title = "Row2"
idx=3: category = "Section1" / title = "Row0"
idx=4: category = "Section1" / title = "Row1"
idx=5: category = "Section2" / title = "Row0"
idx=6: category = "Section2" / title = "Row1"
How do I populate a tableView from this dataArray ? (of course, the sections and rows need to look according to the array's content)
Upvotes: 0
Views: 254
Reputation: 158
Populating sections and rows from a single array is not a good idea. You already noticed it's overly complicated and not stable at all.
The only case in which it would be doable is if your array always has the same amount of rows in each section (section 1 always 3 elements, section 2 always 2, etc.). Like this, you could always know the offset at which your section starts (0 for section 0, 3 for section 1 and so on).
If and only if this is your case, you could do it like so
let offsets = [0,3,5]
let dataEntry = myDataArray[offsets[indexPath.section]+indexPath.row]
But I can't stress this enough: This is in no way good practice and should be avoided altogether.
Upvotes: 1