Why does a keyPath subscript on an instance of a class require a mutatable variable?

A WritableKeyPath is a key path that modifies its root value in-place. Even on a class type, a WritableKeyPath could rebind the reference, which would require that the variable containing the reference be mutable. For instance, if we added the identity key path, it would be a WritableKeyPath, and you wouldn't want to be able to allow changing an immutable class reference through it:

let x = NSObject()
x[keyPath: \.self] = NSObject()  // \.self is a WritableKeyPath, but `x` can't be rebound

A ReferenceWritableKeyPath modifies state through a reference, such as a class reference, and does not modify that reference, which is what you want when talking about mutable class properties.

4 Likes