无法在SwiftUI的当前上下文中推断闭包类型

时间:2019-07-01 11:47:25

标签: ios swiftui

我正在尝试在SwiftUI中使用ForEach在列表中传递简单的字符串数组。

  • 这是我的代码

    import SwiftUI
    
    struct ContentView : View {
    var testArry:[String] = ["1", "a", "c"]
    var body: some View {
    List {
        ForEach(testArry) { obj in
            Text("test")
        }
      }
    }
    }
    
    #if DEBUG
    
    struct ContentView_Previews : PreviewProvider {
     static var previews: some View {
       ContentView()
     }
    }
    #endif
    
  

错误:无法在当前上下文中推断闭包类型

4 个答案:

答案 0 :(得分:3)

或者,您可以像这样使用.identified(by: \.self)

import SwiftUI

struct ContentView : View {

    var testArry:[String] = ["1", "a", "c"]

    var body: some View {
        List {
            ForEach(testArry.identified(by: \.self)) { obj in
                Text("test")
            }
        }
    }
}

答案 1 :(得分:1)

This是正确的答案。 ForEach方法签名已在Xcode 11 Beta 5中更改,并且identified(by:)方法已被弃用:

public struct ForEach<Data, ID, Content> where Data : RandomAccessCollection, ID : Hashable

自动完成功能显示为:

ForEach(Data, id: KeyPath<Data.Element, ID>, content: (Data.Element) -> Content)

因此,当使用Xcode 11 Beta 5时,您的代码将是:

import SwiftUI

struct ContentView : View 
{
  var testArry:[String] = ["1", "a", "c"]
  var body: some View 
  {
    List 
    {
        // The updated ForEach method, as of Xcode 11 Beta 5
        ForEach(testArry, id: \.self)
        { obj in
            Text("test")
        }
    }
  }
}

答案 2 :(得分:0)

您需要在数组上使用.identified(by: \.self),以使SwiftUI将值本身用作标识符。因此,您应该使用以下代码来更改代码。

struct ContentView : View {
    var testArry:[String] = ["1", "a", "c"]
    var body: some View {
        List {
            ForEach(testArry.identified(by: \.self)) { obj in
                Text("test")
            }
        }
    }
}

答案 3 :(得分:0)

尝试如下所示的符合可识别协议:-

struct ContentView: View {
    var testArry: [TestArray] = [TestArray(value: "1"), TestArray(value: "a"), TestArray(value: "c")]
    var body: some View {
        List {
            ForEach(testArry) { obj in
                Text("\(obj.value)")
            }
        }
    }
}
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
class TestArray: Identifiable {
    let value: String
    init(value: String) {
        self.value = value
    }
}