'SwiftUI Bug: Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
I create a struct
struct Row: Identifiable, Hashable {
var id = UUID()
var label: String
var image: String
var value: String
var color: Color
var view: View
}
and I want to put View into an array as my destination View
var array: [Row] = [
Row(label: "All", image: "music.quarternote.3", value: "1031", color: Color.blue),
Row(label: "Fresh", image: "heart.fill", value: "59", color: Color.green),
Row(label: "Soon", image: "play.fill", value: "3619", color: Color.orange),
Row(label: "Expired", image: "stopwatch", value: "165:14", color: Color.red),
]
should I create a class, or there's another way can fix it??
Solution 1:[1]
I believe there is some mismatch there between struct, struct of type View, and class.
If I understood what you need, you can have the data in the struct, then the view in another struct of type View. And in your main view, you put it all together.
Here's how it works:
Your data:
struct Row: Identifiable, Hashable {
var id = UUID()
var label: String
var image: String
var value: String
var color: Color
}
Here's the view of your row:
struct RowView: View {
let row: Row
var body: some View {
HStack {
Text(row.label)
Image(systemName: row.image)
.foregroundColor(row.color)
Text(row.value)
}
}
}
Here's how you put it all together:
struct Example: View {
// Your data comes here
let array: [Row] = [
Row(label: "All", image: "music.quarternote.3", value: "1031", color: Color.blue),
Row(label: "Fresh", image: "heart.fill", value: "59", color: Color.green),
Row(label: "Soon", image: "play.fill", value: "3619", color: Color.orange),
Row(label: "Expired", image: "stopwatch", value: "165:14", color: Color.red),
]
var body: some View {
VStack {
ForEach(array) { row in
// Your view is called here
RowView(row: row)
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HunterLion |

