[英]Iterate over array of `AnyShape` in `ForEach`
我試圖在我的View
中迭代AnyShape
數組——這導致錯誤Generic struct 'ForEach' requires that 'AnyShape' conform to 'Hashable'
。
這是我的ObservableObject
:
class ViewModel: ObservableObject {
var shapes: [AnyShape] = [
.init(Rectangle()),
.init(RoundedRectangle(cornerRadius: 10.0))
]
}
這是導致上述錯誤的我的View
:
struct ContentView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
ForEach(viewModel.shapes, id: \.self) { shape in
//display the shape
}
}
}
我該怎么做才能完成這項工作?
根據我得到的提示,我設法像這樣將AnyShape
包裝到我自己的struct
中(這很明顯,但我需要一些推動):
struct MyShape: Identifiable {
let id: UUID = .init()
let shape: AnyShape
}
struct ContentView: View {
let shapes = [
MyShape(shape: AnyShape(Rectangle())),
MyShape(shape: AnyShape(RoundedRectangle(cornerRadius: 10.0)))
]
var body: some View {
ForEach(shapes) { shape in
shape.shape
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.