Add or remove objects from an array based on didSelectRowAtIndexpath in Swift 3

Viewed 1461

I am working on expandable tableView where I need to add or remove the objects based on didSelectRowAtIndexpath. I was able to add the selected item into an array but the problem is when I am trying to remove the selection from array.

This is the error I am getting:

cannot invoke index with an argument list of type (of:any)

Here is my code:

func expandableTableView(_ expandableTableView: LUExpandableTableView, didSelectRowAt indexPath: IndexPath) {
    let selectedService = arrData[indexPath.section].Children?[indexPath.row].EnglishName ?? ""
    let inPrice = arrData[indexPath.section].Children?[indexPath.row].InPrice ?? 0

    print("service and price : \(selectedService) \(inPrice)")

    let selectedItem = (" \(selectedService) \(inPrice)")
    let cell: UITableViewCell? = expandableTableView.cellForRow(at: indexPath)

    if cell?.accessoryType == UITableViewCellAccessoryType.none
    {
        cell?.accessoryType = UITableViewCellAccessoryType.checkmark
        selectionArr.append(selectedItem)
    }
    else
    {
        cell?.accessoryType = UITableViewCellAccessoryType.none
        selectionArr.remove(at: selectionArr.index(of: selectedItem)!)
    }

    print(selectionArr)
}
3 Answers

@AnhPham

Hey, Tried modifying your code and it worked well please go through following for adding item in array and removing from the same on tableview's didselect and diddeselect methods respectively.

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let categoryTableCell = self.categoriesTableview.cellForRow(at: indexPath) as! CategoriesTableCell

    self.tempCategories.append(self.categories[indexPath.row])

    print("tempArray select:\(self.tempCategories)")

}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

    let categoryTableCell = self.categoriesTableview.cellForRow(at: indexPath) as! CategoriesTableCell

    self.tempCategories.remove(at: self.tempCategories.index(of:self.categories[indexPath.row])!)

    print("tempArray deselect:\(self.tempCategories)")

}
Related