AnyKeyPath to Array Index

I am trying to use keypaths to access certain element within an array that is within a struct. I can easily create a keypath to the element within the array but then something weird is happening when I want to cast that keypath to AnyKeyPath. For example:

public struct ArrayExample {
var innerArray: [Int]

let keyPathToInner = \ArrayExample.innerArray[0]

let anyKeyPathToInner = \ArrayExample.innerArray[0] as AnyKeyPath

When I try to cast using 'as', I get the following error:
'WritableKeyPath<ArrayExample, Int>' is not convertible to 'AnyKeyPath'; did you mean to use 'as!' to force downcast?

And when I try to cast using 'as!' I get the following warning:
Forced cast from 'WritableKeyPath<ArrayExample, Int>' to 'AnyKeyPath' always succeeds; did you mean to use 'as'?

Is this bad practice? Or am I doing something wrong?

1 Like

I don’t have an answer, but when I copy your example into a playground I get a runtime error on this line:

let keyPathToInner = \ArrayExample.innerArray[0]
// Fatal error: load from misaligned raw pointer

That's a separate bug, SR-10117.

@xedin, @Joe_Groff, any insights here?

1 Like

I haven't had time to look into the runtime failure yet. So far, it seems to be specific to playgrounds, the REPL and other interactive modes.

I get the warnings/errors outside of the playgrounds, any idea as to why this might be happening?

Terms of Service

Privacy Policy

Cookie Policy