我试图在 @EnvironmentObject
中引用 [Item]
列表,但是在 SwiftUI
中访问它时列表
,我得到了错误。我不明白的是,跟随Apple's Landmark tutorial 时不会弹出此错误。 .
据我所知,[Item]
列表正在正确加载,因为我可以将其打印出来并使用它执行其他功能。它只是在将它用于 SwiftUI
List
时出错,我错过了什么吗?
ItemHome.swift:
struct ItemHome : View {
@EnvironmentObject var dataBank: DataBank
var body: some View {
List {
ForEach(dataBank.itemList) { item in
Text("\(item.name)") // Type of expression is ambiguous without more context
}
}
}
}
支持代码如下:
项目结构:
struct Item {
var id: Int
var uid: String
var company: String
var item_class: String
var name: String
var stock: Int
var average_cost: Decimal
var otc_price: Decimal
var dealer_price: Decimal
var ctc_price: Decimal
}
数据库.swift:
final class DataBank : BindableObject {
let didChange = PassthroughSubject<DataBank, Never>()
var itemList: [Item] = load("itemsResults.json") {
didSet {
didChange.send(self)
}
}
}
func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
itemsResults.json:
[
{
"id": 1,
"uid": "a019bf6c-44a2-11e9-9121-4ccc6afe39a1",
"company": "Bioseed",
"item_class": "Seeds",
"name": "9909",
"stock": 0,
"average_cost": 0.0,
"otc_price": 0.0,
"dealer_price": 0.0,
"ctc_price": 0.0
},
{
"id": 2,
"uid": "a019bf71-44a2-11e9-9121-4ccc6afe39a1",
"company": "Pioneer",
"item_class": "Seeds",
"name": "4124YR",
"stock": 0,
"average_cost": 0.0,
"otc_price": 0.0,
"dealer_price": 0.0,
"ctc_price": 0.0
}
]
最佳答案
显然我错过了确保我的模型(在本例中为 Item
)符合 Identifiable
协议(protocol)的修复。尽管如此,我还是希望 Apple 能更清楚地说明他们的错误消息。
关于swift - Xcode 11 中没有更多上下文的表达式类型不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56683764/