I seem to not fully understand this . I get the error, but not why I’m getting it. So if anyone could explain to me why. Perhaps I’m misunderstanding the timeline of events in iOS.
I’ve got a very simple table with two sections. The datasource looks like this:
let headerTitles = ["Playing", "Substitute"]
var currentLineup: [[Player]] = [[],[]]
// Number of sections in table
func numberOfSections(in tableView: UITableView) -> Int {
return currentLineup.count
}
// Assign title to header label
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section < headerTitles.count {
return headerTitles[section]
}
return nil
}
// Number of rows in this section
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return currentLineup[section].count
}
// configure cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "lineupCell")
let player = currentLineup[indexPath.section][indexPath.row] as Player
cell?.textLabel?.text = player.name
return cell!
}
// MARK: - ReOrder TableView
// Can the cell be moved
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
if currentLineup[indexPath.section].count <= numberOfPlayersOnATeam {
return true
}
return false
}
// Process the cell move
func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to toIndexPath: IndexPath) {
let playerToMove = currentLineup[fromIndexPath.section][fromIndexPath.row]
currentLineup[fromIndexPath.section].remove(at: fromIndexPath.row)
currentLineup[fromIndexPath.section].insert(playerToMove, at: toIndexPath.row)
}
So when my table renders it has two sections with 4 players in each section.
Section 1
Player 1
Player 2
Player 3
Player 4
Section 2
Player 5
Player 6
Player 7
Player 8
If I move a player 4 into section 2 right at the bottom, after player 8, it will crash and say index out of array
. I understand what the error says, but not why I get it. I want to insert player 4 into that array. So what’s issue? I have also tried changing the insert() line to this currentLineup[fromIndexPath.section].insert(playerToMove, at: 0)
This I hoped would mean that every row moved between sections was inserted at position 0 and therefore alleviate this error. So what am I missing here? And what is the the accepted iOS way to deal with this problem?