Is this a bug? I'm not sure why the compiler is unable to infer the key path type or is it unable to pick one specific key path type from the type hierarchy?
struct S {
var a = 42
var b = "swift"
}
func foo<T>(_ path: KeyPath<S, T>) {
switch path {
case \.a: // Type of expression is ambiguous without more context
print("a")
case \.b: // Type of expression is ambiguous without more context
print("b")
default:
break
}
}
I can workaround this in two ways, either by providing the root type explicitly or by adding a special infix operation.
prefix operator ^
prefix func ^ <Root, Value>(
keyPath: KeyPath<Root, Value>
) -> KeyPath<Root, Value> {
return keyPath
}
struct S {
var a = 42
var b = "swift"
}
func foo<T>(_ path: KeyPath<S, T>) {
switch path {
case \S.a:
print("a")
case ^\.b:
print("b")
default:
break
}
}