I have two arrays, one with Strings and one with a custom object.
I've created two different cells respectively. I've added the contents of the two arrays into a third generic array Any. I use the third array (combinedArray) in cellForItem.
var customObjectArray: [customObject] = []
var stringArray = [String]()
var combinedArray = [Any]()
if combinedArray[indexPath.row] is CustomObject {
cell1.LabelName.text = customObjectArray[indexPath.row].caption
cell1.iconView.image = customObjectArray[indexPath.row].icon
return cell1
} else {
let stringName = stringArray[indexPath.row]
cell2.LabelName.setTitle(stringName for: UIControlState())
return cell2
}
let's say customObjectArray has 13 objects and stringObjectArray has 17 objects. I want a separate counter for each array so that it populates them correctly. The way it's working now:
the combinedArray populates all of one type first (i.e. 13 customObjectArray first), then the next type second (i.e 17 stringObjects). The order the combined array isn't necessarily important as I will probably shuffle things around at some point before getting to cellforitem. So when cellforItem goes through the first 13 objects, indexpath.row = 14, and when it gets to the second type of object, it's skipping the first 13 objects and displaying stringObject's 14th element (obviously).
I can't figure out how to start at the beginning of the second array instead of indexPath.row's current position.
I might be totally off base here and likely should be using two sections or something to that nature, but I'm relatively new to iOS dev, so any guidance is appreciated.
Another option would be to enclose the different data types in an enum and add all the data to your combined array in whatever order you would like.
enum DataHolder {
case stringType(String)
case customType(CustomObject)
}
var combinedArray: [DataHolder]
This gives you a single type for the data and a way to distingue between the cell types.
Inside of the cellForItem
perform a switch on the combinedArray
switch combinedArray[indexPath.row] {
case .stringType(let stringValue):
let cell = tableView.dequeueReusableCell(withIdentifier: "StringCell", for: indexPath) as! StringObjectCell
cell.labelName.text = stringValue
case .customType(let customData):
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomObjectCell
cell.labelName.text = customData.caption
cell.iconView.image = customData.icon