【发布时间】:2020-08-05 17:25:08
【问题描述】:
我是 swift 新手,需要定义某种形式的全局字典,以便我可以在整个项目中访问内容。我的理解是结构类可以用于此
我创建了一个结构并为其附加了值,现在我想访问视图中的每个值
这是我的产品结构
struct Product {
let name: String
let aisleNo:Int
let location_section: Int
let location_zone: String
let productPrice: Int
}
然后创建一个全局
import Foundation
struct Global {
static var productList = [Product]()
}
这就是我将许多产品附加到产品的方式
class SearchResult : ObservableObject {
var productList = [Product]()
//There could be hundreds of product in the array
for product in productArray {
let productName = product.productName!
let aisleNo = product.productLocation_aisle.value!
let location_section = product.productLocation_section.value!
let location_zone = product.productLocation_zone!
let productPrice = product.productPrice.value!
let product_real_id = product._id!
Global.productList.append(Product(name: productName, aisleNo: aisleNo, location_section: location_section, location_zone: location_zone, productPrice: Int(productPrice)))
}
这是我想要显示产品内容的搜索结果视图
struct SearchResultView: View {
var searchResults = Global.productList
var body: some View {
VStack {
List {
ForEach(model.searchResults, id: \.self) { text in
Text(text)
}
}
}
}
}
我似乎可以让它显示在 searchResultView 中。做错了什么? 我不断收到此错误
通用结构 'ForEach' 要求 'Product' 符合 'Hashable' Initializer 'init(_:)' 要求 'Product' 符合 'StringProtocol'
【问题讨论】:
-
请在我的编辑中查看并实施最新更改
-
@JulianSilvestri 谢谢。它可以解决可哈希错误。但是你知道如何修复第二个错误初始化程序'init(_:)' 要求 'Product' 符合 'StringProtocol'
-
字符串协议错误没有随着哈希值消失吗?
-
@JulianSilvestri 不,它没有