【问题标题】:Generic parameter 'SelectionValue' could not be inferred无法推断通用参数“SelectionValue”
【发布时间】:2026-01-22 17:30:01
【问题描述】:

我可能遗漏了一些东西,但为什么这对 Picker 工作得很好,但对 List 却不行?我不明白为什么它抱怨缺少参数类型。

struct ContentView: View {
enum FooBar: CaseIterable, Identifiable {
    public var id : String { UUID().uuidString }
    
    case foo
    case bar
    case buzz
    case bizz
}

@State var selectedFooBar: FooBar = .bar

var body: some View {
    VStack {
        Picker("Select", selection: $selectedFooBar) {
            ForEach(FooBar.allCases) { item in
                Text(self.string(from: item)).tag(item)
            }
        }
        
        List(FooBar.allCases, selection: $selectedFooBar) { item in
            Text(self.string(from: item)).tag(item)
        }
        
        Text("You selected: \(self.string(from: selectedFooBar))")
    }
}


private func string(from item: FooBar) -> String {
    var str = ""
    
    switch item {
    case .foo:
        str = "Foo"
        
    case .bar:
        str = "Bar"
        
    case .buzz:
        str = "Buzz"
        
    case .bizz:
        str = "Bizz"
    }
    return str
}
}

我试图找到解释和例子,但找不到任何东西。

【问题讨论】:

    标签: swiftui swiftui-list


    【解决方案1】:

    如果您将列表提取到 body 之外的它自己的变量中:

    var list: some View {
            List(FooBar.allCases, selection: $selectedFooBar) { item in
                Text(self.string(from: item)).tag(item)
            }
        }
    

    ...您收到此错误:“无法使用类型为 '([ContentView.FooBar], selection: Binding, @escaping 的参数列表调用类型 'List<_ _>' 的初始化程序(ContentView.FooBar) -> 一些视图)'"

    看起来您正在尝试使用来自 Picker on List 的相同初始化程序,但它们完全不同。也许这就是你要找的:

    List {
                ForEach(FooBar.allCases) { item in
                    Text(self.string(from: item)).tag(item)
                }
            }
    

    【讨论】:

      【解决方案2】:

      所选项目的选择器类型正确FooBar,但列表类型错误。如果你使用Set&lt;String&gt; 那么编译器不会抱怨

      @State var selectedFooBar: FooBar = .bar
      @State var selectedItems: Set<String>
      
      var body: some View {
          VStack {
              Picker("Select", selection: $selectedFooBar) {
                  ForEach(FooBar.allCases) { item in
                      Text(self.string1(from: item)).tag(item)
                  }
              }
      
              List(FooBar.allCases, selection: $selectedItems) { item in
                  Text(self.string1(from: item))
              }
      
      
      
              Text("You selected: \(self.string1(from: selectedFooBar))")
          } 
      

      请注意,列表需要处于“编辑模式”才能使用选择。

      【讨论】: