didSet is not calling

Hello,

I have a new problem.

class Group {

        var selected : Int

        class Item {
            var name : String
            @Published var isSelected : Bool
            ...
        }

        var items : [Item] {
            didSet {
                for item in self.items {
                    if(item.isSelected) {
                        selected += 1.0
                    }
                }
            }
        }

    }

didSet is not executed if isSelected is changed.

Classes are reference types, which means that if you change the properties of a class, then the class itself does not change. Item would have to be a value type (e.g, a struct or enum) for this to work.

2 Likes

Does anyone know a workaround?

Option 1:
Change Item to struct

Option 2:
Change selected to a computed property and remove didSet

Option 3
Subscribe to the changes of isSelected as shown below:

class Group {
    
    var selected : Int = 0
    private var cancellables = [Cancellable]()
    
    class Item {
        var name : String = ""
        @Published var isSelected : Bool = false
    }
    
    var items : [Item] = [] {
        didSet {
            cancellables = []
            selected = 0
            for item in self.items {
                let cancellable = item.$isSelected.sink { [weak self] newIsSelected in
                    self?.selected += newIsSelected ? 1 : -1
                }
                cancellables.append(cancellable)
            }
        }
    }
}
Terms of Service

Privacy Policy

Cookie Policy