I've encountered an unexpected outcome with KeyPath and I'm trying to understand how I'm getting to it. Consider this playground:
Expected:
The if-let
should fail because foo.child
is nil
.
Actual:
The if-let
succeeds, but value
is "nil" (nil-ish?) In a debugger instead of the Playground it appears as: (Foo.Foo?) nil
It's AnyKeyPath?
If we drop AnyKeyPath
in favor of an exactly-typed array things now work as expected:
But that's impractical. The whole point of AnyKeyPath
is to enable collections of KeyPaths with different specializations, no?
A guess?
value
is actually an Optional<Foo>
, which satisfies Any
, but is transparently unwrapped to nil
by the debugger and the console in the Playground, so it appears as nil
, which is entirely misleading.
Of course, trying if value == nil
inside the if-let
body fails (and the compiler warns it's always going to fail). So the if-let
didn't unwrap the optional valueType
from the AnyKeyPath
?
Can someone confirm that's what's happening here? I can work around it, I just want to make sure I have an explanation.