无法解决"Type of expression is ambiguous without more context"错误。有人可以检查我的代码吗?



我对 SwiftUI 相对较新,有时会遇到错误并通过互联网搜索来解决它们,但这次我找不到任何解决我的问题的方法,并决定在这里寻求一些帮助,堆栈溢出。我希望下面的代码可以帮助您找到我的问题。

我的两个结构都是可识别的,我实际上在同一视图中使用了 ShoppingList 结构,以相同的技术制作它的列表,并且它没有错误地工作。但是当我尝试将ForEach用于ShoppingList结构体的变量(这也是一个结构并且符合可识别协议(时,我收到此错误"表达式类型不明确,没有更多上下文">

这是我得到错误的观点:

struct ListDetailView: View {
@EnvironmentObject var session: SessionStore
var item: ShoppingList
@State private var isAddNewViewActive: Bool = false
var body: some View {
List {
Section(header: Text("Products")) {
ForEach(self.item.products, id: .id) { product in <<<--- ERROR LINE
Text(product.name)
}
}
Section(header: Text("")) {
Button(action: { self.isAddNewViewActive.toggle() } ) {
Text("Click to add new product")
}
}
}
.listStyle(GroupedListStyle())
.navigationBarTitle(self.item.name)
.sheet(isPresented: $isAddNewViewActive) {
AddNewItemView(session: self.session, item: self.item, isViewActive: self.$isAddNewViewActive)
}
}
}

这些是代码中的结构

struct ShoppingList: Identifiable, Equatable {
var id: UUID
var name: String
var coverPhoto: String
var products: [Product]
init(id: UUID = UUID(), name: String, coverPhoto: String = "cart", products: [Product] = [Product]()) {
self.id = id
self.name = name
self.coverPhoto = coverPhoto
self.products = products
}
mutating func addProduct(product: Product) {
products.append(product)
print(products)
}
}
struct Product: Identifiable, Equatable {
var id: UUID
var name: String
var brand: String
var imageURL: String
var links: [Int: String]
var description: String
init(id: UUID = UUID(), name: String, brand: String = "", imageURL: String = "", links: [Int: String] = [:], description: String = "") {
self.id = id
self.name = name
self.brand = brand
self.imageURL = imageURL
self.description = description
self.links = links
}
}

提前感谢所有 StackOverflow 社区。

我正确符合平等协议

struct ShoppingList: Identifiable, Equatable {
static func == (lhs: ShoppingList, rhs: ShoppingList) -> Bool {
return lhs.id == rhs.id && rhs.id == lhs.id
}
var id: UUID()
...
init(name: String, brand: String = "", imageURL: String = "", links: [Int: String] = [:], description: String = "") {
...
}
}

无需初始化 UUID,UUID(( 将自行生成

显然,我在此处发布的代码片段的完全不相关的部分(当我单击有错误的视图上的按钮时弹出的工作表视图(中存在错误,这导致了错误:/

我在这里发布的代码工作正常。

最新更新