Tutorial 2: Editing existing checklist items. Where do you save edited ojbects to the items array?

Hey all,

could you pls help me to understand how existing items are saved in the var items: [ChecklistItem] array after they were edited?
The delegate method in CheckListViewController is

func addItemViewController(_ controller: AddItemViewController, didFinishEditing item: ChecklistItem) {
    if let index = items.index(of: item) {
        let indexPath = IndexPath(row: index, section: 0)
        if let cell = tableView.cellForRow(at: indexPath) {
            configureText(for: cell, with: item)
        }
    }
    dismiss(animated: true, completion: nil)
}

I understand that you find the “equal” object in the items array, but where do you write the edited item in items[]?
For example you had first “Walk the dog” → Edited it to “Walk the cat”. If you scroll cell for rowAtIndexPath is triggered and this method looks in the items array and should read “Walk the dog”, because you never wrote to this array?

I looked up the Swift Standard Library for index(of: )

var students = [“Ben”, “Ivy”, “Jordell”, “Maxime”]
if let i = students.index(of: “Maxime”) {
students[i] = “Max”
}
print(students)
// Prints “[“Ben”, “Ivy”, “Jordell”, “Max”]”

and there they rewrite the value in the students array.
I can’t find it in our code. Has it to do something with tag?

Thanks in advance

The ChecklistItem object is already in the array. Since you change that ChecklistItem object directly, what is in the array also changes (because those two things are the same thing).

This might be difficult to understand at first, but ChecklistItem is a reference type and the array actually contains a reference to the ChecklistItem object. When you tap this item to edit it, AddItemViewController is given another reference to that same ChecklistItem object.

Since both references – the one from the array and the one from AddItemViewController – point to the same ChecklistItem object, changing the ChecklistItem in one place also changes it in another.

The reason the behavior in your other example is different, is that the array now contains string objects. Unlike ChecklistItem objects, strings are value types, not reference types.

The book will go into this topic in more detail later, but if you want to read some more about reference types and value types, then check out this tutorial: https://www.raywenderlich.com/112027/reference-value-types-in-swift-part-1

Ty hollance, perfectly explained. I understand it. Thank you very much :+1: