代码之家  ›  专栏  ›  技术社区  ›  Joe Scotto

将结构作为泛型类型传递并访问该泛型类型的属性

  •  0
  • Joe Scotto  · 技术社区  · 2 年前

    我正在开发一个Swift包,其中有一个选项是传入泛型类型( Person )然后 GenericStruct 可以对传入的类型使用属性。问题显然是泛型 T 不知道传递了什么。 是否有方法定义要在泛型类型上访问的属性 T ?

    struct Person: Equatable {
        var name: String
        var height: Double
    }
    
    struct ContentView: View {
        @State private var james = Person(name: "James", height: 175.0)
        
        var body: some View {
            GenericStruct(person: $james)
        }
    }
    
    struct GenericStruct<T: Equatable>: View {
        @Binding var person: T
        
        var body: some View {
            Text(person.name)) // This line.
        }
    }
    

    我想特别传入要访问的属性 传递给时 通用结构 。这处房产不会总是 name 它可以是我定义的任何东西 例如

    GenericStruct(person: $james, use: Person.name)
    
    1 回复  |  直到 2 年前
        1
  •  4
  •   Rob Napier    2 年前

    这不正是一个协议吗?

    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)