What is wrong with this `WritableKeyPath`?

I have a class where I want to reference a certain storage dictionary by some condition. To reduce writing the same code multiple times I wanted to use key-paths to get a writable reference to mutate in-place on self. However I hit a compile-time-error which is a little confusing.

class Test {}

class Object {
  let storage: Storage

  init() {
    storage = Storage(branch: .init(lhs: [:], rhs: [:]))
  }

  func `mutate`(with condition: Bool, id: String, value: Test) {
    let storagePath: WritableKeyPath = condition
      ? \Object.storage.branch.lhs
      : \Object.storage.branch.rhs
    self[keyPath: storagePath][id] = value // error: Cannot assign to immutable expression of type 'Test?
  }
}

extension Object {
  final class Storage {
    let branch: Branch

    init(branch: Branch) {
      self.branch = branch
    }
  }
}

extension Object.Storage {
  final class Branch {
    var lhs: [String: Test]
    var rhs: [String: Test]

    init(lhs: [String: Test], rhs: [String: Test]) {
      self.lhs = lhs
      self.rhs = rhs
    }
  }
}
2 Likes

@timv solved the mystery on Slack. Instead of WritableKeyPath it should be ReferenceWritableKeyPath. :roll_eyes:

8 Likes