简体   繁体   English

SwiftUI - 显示符合协议和 ForEach 的元素的视图

[英]SwiftUI - View showing Elements conforming to a Protocol and ForEach over them

I want to write a SwiftUI View ListOfMyStruct that operates on an Array of Elements conforming to a given Protocol MyProtocol .我想编写一个 SwiftUI 视图ListOfMyStruct ,它对符合给定协议MyProtocol的元素数组进行操作。
The example works, but of course I need to ForEach over the Elements of the Array (as tried in the commented out lines).该示例有效,但当然我需要对数组的元素进行 ForEach(如在注释掉的行中所尝试的那样)。
Using ForEach, I get: Value of protocol type 'MyProtokoll' cannot conform to 'Hashable';使用 ForEach,我得到:协议类型“MyProtokoll”的值不能符合“Hashable”; only struct/enum/class types can conform to protocols .只有 struct/enum/class 类型可以符合协议
If I try to let MyProtocol conform to Hashable I get: Protocol 'MyProtokoll' can only be used as a generic constraint because it has Self or associated type requirements .如果我尝试让MyProtocol符合Hashable我得到: Protocol 'MyProtokoll' can only be used as a generic constraint because it has Self or associated type requirements

How can I archive this?我该如何存档?

struct PTest: View {
  @State var allMyStruct : [MyStruct] =
    [ MyStruct(name: "Frank Mueller", myshortName: "fm", a_lot_of_other_sttributes: "bla"),
      MyStruct(name: "Tom Smith", myshortName: "ts", a_lot_of_other_sttributes: "bla")
    ]

  var body: some View {
    VStack {
      Text("Hello, world!")
      ListOfMyStruct(elements: allMyStruct)
    }
    .frame(width: 400, height: 400, alignment: .center)
    .padding()
  }
}

struct ListOfMyStruct: View {
  var elements : [MyProtokoll]

  var body: some View {

    HStack {
      Text("Elements of MyProtocol: ")
      Text("\(elements[0].shortName() )")
      Text("\(elements[1].shortName() )")

//      ForEach(elements, id: \.self) { myProtocol in
//        Text("\(myProtocol.shortName())")
//      }
    }
  }
}


//protocol MyProtokoll : Identifiable, Hashable  {
protocol MyProtokoll {
  var id: String { get }
  func shortName() -> String
}

struct MyStruct :MyProtokoll {

  var id : String {myshortName}
  var name : String
  var myshortName :String
  var a_lot_of_other_sttributes : String

  func shortName() -> String {
    myshortName
  }
}

It is possible to use iteration by indices.可以通过索引使用迭代。

Here is a fixed part (tested with Xcode 12.4)这是一个固定部分(用 Xcode 12.4 测试)

    HStack {
//      Text("Elements of MyProtocol: ")
//      Text("\(elements[0].shortName() )")
//      Text("\(elements[1].shortName() )")

        ForEach(elements.indices, id: \.self) { i in
           Text("\(elements[i].shortName())")
        }
    }

also the solution is to specify id explicitly, like解决方案也是明确指定id ,例如

  ForEach(elements, id: \.id) { myProtocol in
    Text("\(myProtocol.shortName())")
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM