这不正是一个协议吗?
protocol NameProviding {
var name: String { get }
}
struct GenericStruct<T: Equatable & NameProviding>: View { ... }
或者这个问题还有更微妙的部分吗?
最好的方法是传递一个字符串绑定:
struct GenericStruct: View {
@Binding var text: String
var body: some View {
Text(text)) // This line.
}
}
GenericStruct(text: $james.name)
但关键路径也是可能的。在这种特殊情况下,它只是有点尴尬和不那么灵活:
// Should be the syntax, but I haven't double-checked it.
struct GenericStruct<T: Equatable>: View {
@Binding var person: T
var use: KeyPath<T, String>
var body: some View {
Text(person[keyPath: use]))
}
}
GenericStruct(person: $james, use: \.name)