Сев*_*ева 10 foreach swift swiftui
我不明白可能是什么问题
例如,我有一些 Json 是
[
{
"id": 1,
"title": "Title",
"info": "info",
"brand": "brand",
"model": "MODEL",
"make_year": year,
"properties": [
{
"id": 1,
"icon": "ic_rgb",
"label": "color",
"value": "red"
},
{
"id": 2,
"icon": "ic_car",
"label": "type",
"value": "value"
},
{ "id": 3,
"icon": "ic_fuel",
"label": "fuel",
"value": "gas"
}
],
},
{
"id": 2,
"title": "title2",
"message": "massage2",
"info": "wow you are amazing, thanks for the help",
"properties": [
{
"id": 11,
"icon": "ic_rgb",
"label": "2color",
"value": "2blue"
},
{
"id": 21,
"icon": "ic_car",
"label": "2type",
"value": "2cgh"
},
{ "id": 31,
"icon": "ic_fuel",
"label": "fuel",
"value": "test"
},
....
],
}
]
Run Code Online (Sandbox Code Playgroud)
还有我的模特
struct Unicards: Hashable, Codable, Identifiable {
var id: Int
var title: String?
var info: String?
var brand: String?
var model: String?
var make_year: Int?
var messege: String?
var messege_color: String?
var price: String?
var price_currency: String?
var price_tooltip: String?
var properties: [HPropert]?
struct HPropert: Hashable, Codable, Identifiable {
var id: Int
var icon: String?
var label: String
var value: String
}
Run Code Online (Sandbox Code Playgroud)
还有什么问题...我正在尝试为属性的水平集合创建 forEach 方法
我部分成功了,我用嵌套数组实现了这个方法,它甚至正确生成了单元格的数量。哇!)
但是当我想通过索引为文本分配值时,它会给出一个错误......
我实际上无法理解这个问题,因为数组已经由单元格对象的数量计算和创建。
但是当我要求公式分配值时??我得到
Cannot convert value of type '[Unicards.HPropert]' to expected argument type 'Range<Int>'
Run Code Online (Sandbox Code Playgroud)
我的代码如下
struct Card_cell_rowOfCheracteristics: View {
var data2: Unicards
var body: some View {
let properties = data2.properties!
return VStack() {
// Text("thanx bro!. have a nice day")
// .font(.system(size: 14))
// .font(.headline)
// .fontWeight(.light)
// .multilineTextAlignment(.leading)
ScrollView(Axis.Set.horizontal) {
HStack {
ForEach(properties) { card in <--- Cannot convert value of type '[Unicards.HPropert]' to expected argument type 'Range<Int>'
VStack {
Image()
.resizable()
.scaledToFit()
.frame(width: 34, height: 34)
VStack {
Text(properties[card].label)
.font(.system(size: 14))
.fontWeight(.medium)
Text(properties[card].value)
.font(.system(size: 14))
}
}
}
}
}
}
}
struct Card_cell_rowOfCheracteristics_Previews: PreviewProvider {
static var previews: some View {
Card_cell_rowOfCheracteristics(data2: PlatesData[0])
}
}
}
Run Code Online (Sandbox Code Playgroud)
但如果我说
properties[0].label
Run Code Online (Sandbox Code Playgroud)
没有错误发生
Und*_*Fox 13
此错误表示您data2.properties!的类型不符合Identifiable协议。说,如果您data2.properties!的类型是 A,则尝试执行以下操作:
struct A: Identifiable {
...
var id: String {
return /*some ID*/
}
...
}
Run Code Online (Sandbox Code Playgroud)
这应该可以解决“幕后”的问题。
尝试做这样的事情:
ForEach(properties) { card in
.
Text(card?.label)
.
}
Run Code Online (Sandbox Code Playgroud)
我认为问题在于,card当您迭代数组时,数组中的每个元素都被称为 a 。因此,要获取数组中该元素的属性,您可以通过以下方式执行此操作:card?.[property_name]
| 归档时间: |
|
| 查看次数: |
8820 次 |
| 最近记录: |