DCDC DCDC - 3 months ago 13
iOS Question

Swift - How to pair variables from two Independent classes?

Imagine we have two classes A and B. A is a nonspeciffic class and B is a subclass of a ViewController

How to make B instance variable equal to A instance variable?

A class cannot hold an instance of B, and mutually B cannot hold an instance of A.

The exact thing I'd like to achieve is that B class variable is updated to the value of A class variable.

Delegation is not possible because none of the classes holds the other's instance.
How should I approach such problem? KVO? I read that it rather shouldn't be used due to its flaws.

Answer

If neither class can hold a reference to the other one, they both need to hold a reference to an object of a third class, which holds the actual value. Properties inside A and B need to reference the corresponding property in C:

Diagram

class C {
    var prop : String = "hello"
}
class A {
    var prop : String {
        get { return c.prop }
        set(v:String) { c.prop = v }
    }
    let C:c
    init(c:C) {
        self.c = c
    }
}
class B : NSViewController {
    var prop : String {
        get { return c.prop }
        set(v:String) { c.prop = v }
    }
    let C:c
    init(c:C) {
        self.c = c
    }
}