代码之家  ›  专栏  ›  技术社区  ›  dwaz

SwiftUI List“无法推断泛型参数'S'”

  •  0
  • dwaz  · 技术社区  · 5 年前

    我正在尝试显示一个SwiftUI列表并得到错误,“无法推断泛型参数”。我试着把它改成ForEach,但是在ForEach上得到了相同的错误。错误的位置在下面有注释。

    import SwiftUI
    import Combine
    
    @available(iOS 13.3, *)
    struct MyCustomerListView: View {
        @ObservedObject var custObservable: CustomersObservable = CustomersObservable()
    
        init()
        {
            UITableView.appearance().tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Double.leastNonzeroMagnitude))
        }
    
        var body: some View {
            List(custObservable.customers) { cust in  //  <-- Error is here on List
                NavigationLink(destination: MultipleSignatureView(customer: cust)) {
                    Text(cust.companyName)
                }
            }.listStyle(GroupedListStyle())
        }
    }
    
    @available(iOS 13.3, *)
    class CustomersObservable: ObservableObject {
        @Published var customers: [Cust] = [Cust]()
    
        init() {
            customers.append(contentsOf: [
                Cust(id: "u", companyName: "Uinta"),
                Cust(id: "v", companyName: "victor"),
                Cust(id: "w", companyName: "wasden")
            ])
        }
    }
    
    @available(iOS 13.3, *)
    class Cust: Identifiable {
        var id: String
        var companyName: String
    
        init(id: String, companyName: String) {
            self.id = id
            self.companyName = companyName
        }
    }
    

    0 回复  |  直到 5 年前
        1
  •  0
  •   dwaz    5 年前

    我终于明白了。这个错误一点也不直观。我的问题在于这个代码:

    NavigationLink(destination: MultipleSignatureView(customer: cust)) { // <-- wrong type passed
        Text(cust.companyName)
    }
    

    之前:

    import SwiftUI
    
    @available(iOS 13.3, *)
    struct MultipleSignatureView: View {
        var customer: String     // <-- It was choking here. Cust object was being passed
        var body: some View {
            Text(customer)
        }
    }
    

    之后:

    import SwiftUI
    
    @available(iOS 13.3, *)
    struct MultipleSignatureView: View {
        var customer: Cust               // <-- Now it takes a Cust object
        var body: some View {
            Text(customer.companyName)
        }
    }
    
    推荐文章