Monitoring Key Values ​​in Swift 4

I have the following code in my Swift 4 project.

class DishesTableViewController : UITableViewController { private var token :NSKeyValueObservation? @objc dynamic private(set) var dishes :[Dish] = [] override func viewDidLoad() { super.viewDidLoad() // configure the observation token = self.observe(\.dishes) { object, change in // change is always nil print(object) print(change) } updateTableView() } 

Whenever the array of dishes changes, the observation is triggered. But my question is how can I get the actual change that happened. How can I access the actual Dish object that caused the change.

+5
source share
1 answer

I think the reason change appears with nil is because you did not specify parameters.

Rewrite as follows:

 override func viewDidLoad() { super.viewDidLoad() // configure the observation token = self.observe(\.dishes, options: [.new,.old]) { object, change in print(object) let set1 = Set(change.newArray!) let set2 = Set(change.oldArray!) let filter = Array(set1.subtract(set2)) print(filter) } updateTableView() } 

Please note that I have a little clue about your Dish object. I assume that you followed the Equatable protocol, and this is a necessary step for the solution to work.

+5
source

Source: https://habr.com/ru/post/1272208/


All Articles