How to iterate/foreach array in SwiftUI
This seems a very complex way to implement a struct:
struct DeckColor {
var name: String
var desc: String
}
let deckColors = [
DeckColor(name: "blue", desc: "desc1"),
DeckColor(name: "yellow", desc: "desc2")
]
struct ContentView: View {
var body: some View {
ForEach(0 ..< deckColors.count) { value in
Text(deckColors[value].name)
}
}
}
The way you've implemented it requires dealing with the case that the dictionary does not include a "name"
value. You can do that, but it's uglier and more fragile:
struct ContentView: View {
var body: some View {
ForEach(0 ..< deckColors.count) { value in
Text(deckColors[value]["name"] ?? "default text if name isn't there.")
}
}
}
This works for me
struct ContentView: View {
let deckColors = [
["name": "blue", "desc": "desc1"],
["name": "yellow", "desc": "desc2"],
]
var body: some View {
ForEach(0 ..< deckColors.count, id: \.self) {value in
Text(String(self.deckColors[value]["name"]!))
}
}
}