0

I'm trying to remove an item of an array when the user deselects a cell. I understand why my code it's not working, basically, the array might contain 5 elements and if there are 100 cells and the user selected cell 10, trying to deselect it via indexPath.row would crash since the array has only 5 elements. The point is when the user deselect the cell, it should remove the corresponding element from the array. That's what I'm not sure how to do

var transferUsers = [UserModel]()

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        selectedUsersCount -= 1
        if selectedUsersCount == 0 {
            nextButton.isEnabled = false
        }
        cell.accessoryType = .none
        transferUsers.remove(at: indexPath.row)
    }
}

I tried this answer, but I get an error saying:

Cannot invoke 'index' with an argument list of type '(of: UserModel)'

3
  • What is the relationship/logic between the index path and the array index supposed to be ? The error simply says that UserModel does not conform to Equatable. Commented Aug 24, 2018 at 18:32
  • Actually, there isn't. I just thought about it now when you mentioned it. Commented Aug 24, 2018 at 18:33
  • Um...how many rows are you showing? What does your numberOfRows:inSection: method return? More code would be helpful. Commented Aug 24, 2018 at 18:42

1 Answer 1

1

Okay, so I think you are displaying a list of rows, and when a cell is selected, you add the user to the transferUsers array. The issue with this is that you do not store the location of the selected user.

A quick fix for this would be to have a dictionary, which combines the index path with the user.

var transferUsers: [IndexPath: UserModel] = [:]

then, when a user is selected, you do this:

transferUsers[indexPath] = usersArray[indexPath.row]

and when a user is deselected, you do this:

transferUsers.removeValue(forKey: indexPath)

selectedUsersCount could be a property:

var selectedUsersCount: Int {
    return transferUsers.count
}

to get only the list of selected users, since you have a dictionary, you would do it like this:

transferUsers.values
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the detailed explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.