mtech ac
mtech ac

Reputation: 31

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

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)
}

Upvotes: 3

Views: 1702

Answers (3)

Fatin Wasta
Fatin Wasta

Reputation: 444

@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)")

}

Upvotes: 2

intellignt_idiot
intellignt_idiot

Reputation: 1992

Use indexPath.row instead of selectedItem selectionArr.remove(at: selectionArr.index(of: indexPath.row)!)

Upvotes: 0

Johannes Knust
Johannes Knust

Reputation: 1021

selectionArr.remove(at: selectionArr.index(of: selectedItem)!)

selectedItem is not an Int. You should receive an error:

"Cannot convert value of type 'String' to expected argument type 'Int'"

Maybe you are just searching this one:

selectionArr.remove(at: indexPath.row)

Upvotes: 0

Related Questions