Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate/foreach array in SwiftUI

I have this array of dictionaries.

let deckColors = [
    ["name": "blue", "desc": "desc1"],
    ["name": "yellow", "desc": "desc2"],
]

And my view:

struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) {value in
            Text(deckColors[value]["name"])
        }
    }
}

How can I make it work? Currently getting this error: Protocol type Any cannot conform to StringProtocol because only concrete types can conform to protocols

like image 810
user2641891 Avatar asked Feb 16 '20 23:02

user2641891


1 Answers

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.")
        }
    }
}
like image 132
Rob Napier Avatar answered Nov 05 '22 19:11

Rob Napier