AnyObject and key paths

I came across this error when attempting to apply an AnyKeyPath to an AnyObject:

struct S {
  let object: AnyObject
  let keyPath: AnyKeyPath
  func f() {
    object[keyPath: keyPath]  // 🛑
  }
}

:stop_sign: The root type of a Swift key path cannot be 'AnyObject'

I was curious about the limitation, and the diagnostic is very specific, so following the commit I came to this PR, and then a few layers deeper this comment from @jrose:

I don't think we ever intended to support key paths through AnyObject, since they represent arbitrary Objective-C messages rather than a specific property declaration.

Swift has come a long way since, both in Objective-C interop, and in which AnyObject no longer always relates to Objective-C on platforms like Linux, etc., so I'm curious if the reasoning behind forbidding key paths from being applied still stands? Should it be possible to apply an AnyKeyPath to an AnyObject here?

Strangely, the mere act of assigning the object to a var makes the diagnostic go away, so it is possible to apply the key path:

func f() {
  var object = object
  object[keyPath: keyPath]  // ✅
}

...So I imagine this a bug that should be filed? But what's the correct behavior?

4 Likes