Using WritableKeyPath with actors

I am not sure on how to use WritableKeyPath in an actor (or if it even possible?)
I have this very simple example for demonstration

actor TestActor {
  var testVar: Int = 1
  
  func update(_ target: WritableKeyPath<TestActor, Int>, _ value: Int) {
    self[keyPath: target] = value
  }
  
  func test() {
    self.update(\.testVar, 3)
  }
}

This fails with two error

  1. On the line self[keyPath: target] = value it shows Cannot assign through subscript: 'self' is immutable. I dont see how that is true though, since I can write self.testVar = value in the same method and it mutates without problems. When I replace WritableKeyPath with ReferenceWritableKeyPath the error seems to go away, but I really dont understand why

  2. On the line self.update(\.testVar, 3) it says Cannot form key path to actor-isolated property 'testVar' and I really have no idea what to do about it

Is this something that actors support at all and if not why? There is a good chance I still dont understand actor-isolation properly, but at least on the surface this does not seem like something that should break it

1 Like

For the first error, change WritableKeyPath to ReferenceWritableKeyPath because WritableKeyPath only work on value type whereas the latter works on reference type

2 Likes