Search code examples
iosswiftinheritancesubclasssuperclass

Swift - Call subclass method on change in variable of super class


I have a superclass A and subclass B. Both are ViewControllers. The code is as follows :

class A {
    var a : Bool = false
}

class B : A {
    var b : Int = 10
    func changeB() {
        b = 20
    }
}

So, theres a variable a in class A. Whenever it changes, it should change the variable b of class B i.e. it should call a method changeB() which will update b.

One way to achieve this is use events to call the method changeB() which will update b.

Is there any other way to achieve the same thing?

This is just a template for others to understand. The actual problem is - Class A consist of map view and list view and it handles the switching between 2 views. Class B inherits A and has button on top of the view which should be shown only for list view and not for map view.

So, I want to change my button.isVisible property which is in class B, when the view switches between list view and map view which is handled in class A.


Solution

  • You need to override a in your subclass so that you can call changeB from its setter.

    class B : A {
        var b : Int = 10
        override var a: Bool {
            set {
                super.a = newValue
                self.changeB()
            }
            get {
                return super.a
            }
        }
    
        func changeB() {
            b = 20
        }
    }