Kevin Vugts Kevin Vugts - 1 month ago 12
iOS Question

How to append on didSelectRow and remove on didDeselectRow in swift 3.0

I am trying to make a function that will append a selected row to an array and also remove from array when the row is deselected. Can you guys help me out with this?

Select Row Function:

var exercises = [exercise]() // Array that will be filled by selected rows

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as? exerciseCell
let exercisesSelected = selectedCell?.exerciseNameLbl.text
exercisenames.insert(exercisesSelected!, at: 0)
}


This is my deselect Delegate method:

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as? exerciseCell

if exercisenames.count < 1 {
print("empty array")
}else{
exercisenames.remove(at: indexPath.row)
print(exercisenames)
}
}


Looking forward for any help, thank you!

Kevin.

Answer

You can use a for in loop to remove a specific object in the array.

for (index,value) in exercisenames.enumerate() {
    if value == selectedCell.exerciseNameLbl.text {
        exercisenames.remove(at:index)
    }
}
Comments