How to check whether a key path is writable?

Is there a public API for checking whether an AnyKeyPath instance is a WritableKeyPath, when the WritableKeyPath Root and Value generic parameters are not known?

Since Root and Value are not known, x is WritableKeyPath<Root, Value> can't be used.

Here's the best I could do:

// Implementation detail, not to be user-exposed.
protocol _WritableKeyPath {}
extension WritableKeyPath: _WritableKeyPath {}

public extension AnyKeyPath {
  var isWritable: Bool {
    self is _WritableKeyPath

struct S {
  var mutable: Float
  let immutable: Float
print((\S.mutable).isWritable) // true
print((\S.immutable).isWritable) // false

If no such public API exists, is it acceptable to pitch a public AnyKeyPath.isWritable computed property?

public class AnyKeyPath {
  public var isWritable: Bool { false }


public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> {
  public override var isWritable: Bool { true }
1 Like

Currently there is no way to check and see if an AnyKeyPath or PartialKeyPath is writable. I'm kind of curious about the usefulness of this, because usually, if you want to know if something is writable, you will then want to be able to write to it.

You can check whether a key path is writable by dynamically casting it to WritableKeyPath<Root, Value> for the type you expect to be able to write. Asking whether a key path is writable irrespective of root and value isn't useful, because you wouldn't be able to use it to write anything if you don't the root and value types of what you're trying to write.


Can I ask why you're looking for this? I can't think of a single case where code asking if a key path was writable would be correct to do so.

Thanks for the replies!

I agree that this makes sense, after some thought.

I actually don't have a well-scoped use case - I'm asking this question after a quick chat with a colleague.

The use case is "derived conformances" for "partially codable" types: ideas are raw and the use case isn't tied to key paths, so I don't think it's productive to discuss it in detail.

Yeah, I think you'd want the compile-time notion of mutability there, but if you were limiting it to just stored properties then maybe a run-time-synthesized implementation would work. On your own types, mind you.

Terms of Service

Privacy Policy

Cookie Policy