如何迭代一些符合视图协议的协议数组?



我的目标是创建符合视图协议的SomeProtocol,然后使用它来创建带有ForEach循环的SomeProtocol数组,并使用每个SomeProtocol的body。

目前我有这样的东西:

protocol SomeProtocol: View, Identifable {
var name: String { get }
}
public struct ActualView: View {
let items: [SomeProtocol]
// Error: Protocol 'SomeProtocol' can only be used as a generic constraint because it has Self or associated type requirements
init(items: [SomeProtocol]) {
self.items = items
}
public var body: some View {
VStack {
ForEach(items) { item in
// Error: Value of protocol type 'SomeProtocol' cannot conform to 'Identifiable'; only struct/enum/class types can conform to protocols
Text(item.name)
// Member 'body' cannot be used on value of protocol type 'SomeProtocol'; use a generic constraint instead
item.body
}
}
}

在更短的版本中,我想通过协议传递一些视图,但添加一些额外的信息给它。

您可以使您的ActualView通用,像这样:

protocol SomeProtocol: View, Identifiable {
var name: String { get }
}
struct ActualView<Item: SomeProtocol>: View {
let items: [Item]
var body: some View {
VStack {
ForEach(items) { item in
Text(item.name)
item
}
}
}
}

最新更新