0

In my case, I am loading JSON data into Tableview with help of codable. The tableview multiple select and deselect checkmark options available. Now, I need to Insert selected values into one array and same time if user deselect the cell need to remove relevant value from same array. The stored array data, I am going to use in multiple viewcontroller. How to achieve this?

JSON Codable

// MARK: - Welcome
struct Root: Codable {
    let status: Bool
    let data: [Datum]
}

// MARK: - Datum
struct Datum: Codable {
    let userid, firstname, designation: String?
    let profileimage: String?
}

My Codebase for Tableview Delegate

var studentsData = [Datum]()
var sessionData = [Datum]()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.studentsData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
        let item = self.studentsData[indexPath.row]
        cell.nameCellLabel.text = item.firstname
        cell.subtitleCellLabel.text = item.designation
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let item = self.studentsData[indexPath.row]
        if let cell = tableView.cellForRow(at: indexPath) {
            if cell.accessoryType == .checkmark {
                cell.accessoryType = .none
                // UnCheckmark cell JSON data Remove from array
                if let index = sessionData.index(of:item) {
                    sessionData.remove(at: index)
                }
                print(sessionData)

            } else {
                cell.accessoryType = .checkmark
                // Checkmark selected data Insert into array
                self.sessionData.append(item)
                print(sessionData)
            }
        }
    }
myapp store
  • 173
  • 11
  • By using the below code you can search the particular in the array and remove it easily. if let index = selectedArr.firstIndex(of: item) { selectedArr.remove(at: index) } – thevikasnayak Jul 23 '20 at 17:05

1 Answers1

0

You can remove the item inside the array by searching for its index

let index = try? array.firstIndex(where: { $0. userid == sessionData[indexPath.row].userid })

Or you can use this Checking if an array of custom objects contain a specific custom object

  • but I am using searching, so for searching I used filteredarray. Thats the reason I used item variable. anyway I will try and update you here. Thank you so much for your reply :) – myapp store Nov 02 '19 at 10:00