gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:26:50 25 4
gpt4 key购买 nike

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

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

这是我得到错误的 View :

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 社区。

最佳答案

我正确遵守了 Equatable 协议(protocol)

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()会自行生成

关于ios - 无法解决 "Type of expression is ambiguous without more context"错误。有人可以检查我的代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59996772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com