I spent all evening trying to get the Bronze Challenge to work. One quirk in the code was driving me CRAZY!!! I went with a simple solution. I added a method in the Item Store that just sorted the items in the store into two new “Items” arrays: “overFifty” and “other”. I did that so that I could ask each new array how many Items it was holding: “itemStore.overFifty.count”. I used that to give me the Item count for each section. Simple.
But, when I tried to use those two Items variables in the method call to “cellForRowAt,” the code simply wouldn’t work. I added an “if” statement to check to see if the indexPath.section was in the first section “0”. If so, I set the “item” to the appropriate element of the “other” array of items. Otherwise, I know that we are in the second section “1”, and the “item” should be set to the appropriate element in the “overFifty” array.
Here’s the deal: If you try to use the “item” reference outside of the “if” statement, the code does not work. It only worked when I defined the text for the given label WITHIN the “if” statement. In other words, if you tried to move the line of code “cell.textLabel?.text = item.name” outside of the “if” statement, XCode believes that “item” is not defined and will not let you proceed.
That makes absolutely no sense to me. Why would that be the case???
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
print("Section is: \(indexPath.section). Row is: \(indexPath.row)")
if indexPath.section == 0 {
let item = itemStore.other[indexPath.row]
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = "$\(item.valueInDollars)"
} else {
let item = itemStore.overFifty[indexPath.row]
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = "$\(item.valueInDollars)"
}
return cell
}
}
The above code is clunky, but it does work. I added some orange/bold headers just trying to learn: