Key paths or similar with the target enclosing type not known

I am relative new to Swift, but liking it so far. My current toy project to learn Swift better is something I thought would be easy, but it turned out quite challenging.

Basically, it is a data flow simulation modelling package, and to connect outputs of a model to the inputs, I thought property wrappers with key paths was suitable.

Essentially, doing:

class Foo : Model {
  @Output public y: Double
}

class Bar : Model {
  @Input public var x: Double
}

// Here we connect myFoo.$y to myBar.x

myFoo.y = 42

// now myBar.x is 42

So setting the output property should propagate the set value to all the connected targets (which may be more than one).
This works fine, if we know the class where the input value is located in. But we don't in this case. So invoking the key paths results in type errors implying that there is no x in the Model class, which is technically true I suppose.

I managed to work around this using raw pointers, but that kind of eliminates the use of having property setters being invoked.

I'd guess I am looking for a usable key path like mechanism where we could either use properties declared in sub classes or where the root type is completely unknown, but the value type is known.

Any pointers in the right direction here?

My current understanding is that you're trying to reimplement

ObservableObject.$published.assign(to:)

Is it different?

1 Like

Right, that is indeed pretty much exactly what I am trying to do. Thanks for the pointer :slight_smile:

1 Like