SwiftUI List how can I do this more efficient

I'm new to swiftUI.

There must be a way to make this better.

For example if I add an Item (for example: "name5") to names I have to add a new HStack Block in my Code.

How can I do this more efficient?


import SwiftUI

struct name: View {
     let names = ["name1", "name2", "name3", "name4"]
    var body: some View {
        List {
            VStack {
            HStack {
                Image(names[0])
                Text(names[0])
                }
                HStack {
                    Image(names[1])
                    Text(names[1])
                    }
                HStack {
                    Image(names[2])
                    Text(names[2])
                    }
                HStack {
                    Image(names[3])
                    Text(names[3])
                    }

            }
        }
    }
}

struct monsterList_Previews: PreviewProvider {
    static var previews: some View {
        name()
    }
}


Maybe something like this.

Pseudocode:

foreach i in names.count: 
HStack {
     Image(names[i])
     Text(names[i])
}

if I add an Item to names it should automatically increase the list by the new element.

thanks in advance

Accepted Answer

First of all, you shoud better choose the right topic area: SwiftUI. You will get more chance that more experts of SwiftUI would read your question.


Second, better try to find good tutorials of SwiftUI on the web, many of them include how to use List.


You can write something like this:

struct NameView: View {
    let names = ["name1", "name2", "name3", "name4"]
    var body: some View {
        List(names.indices) { i in
            HStack {
                Image(self.names[i])
                Text(self.names[i])
            }
        }
    }
}

(`name` is not a good name for SwiftUI Views, and type names should start with capital letter.)

SwiftUI List how can I do this more efficient
 
 
Q