Why can you access an associated type but not a generic placeholder from a metatype instance?

I don't know if there's ever a need for it. I gave this some thought after someone said key paths had poor usability.

If I had to work with this…

struct S { var value: Int? }

func setValueIfMatch(instance: S, value: some Any) {

…I would do it like

func cast<Uncast, Cast>(
  _ uncast: Uncast, to: Cast.Type = Cast.self
) throws(CastError) -> Cast {
  guard case let cast as Cast = uncast else { throw .init() }
  return cast
}
struct CastError: Error { }
try? instance.value = cast(value)

…but it seems odd to me that this isn't an option:

if let value = try? cast(value, to: type(of: \S.value).Value) {
  instance.value = value
}

…without

extension KeyPath {
  typealias Value = Value
}
1 Like