Working of List and ForEach in SwiftUI

What’s the difference if we write


myArray is a object of strict which has only two items An id and name

List(self.myArray, id: \.id) { currentArray in

....

}



And




List {

ForEach(self.myArray, id: \.id) { currentArray in

......

}

}
Answered by ChrisFrost in 612763022
If You want to make delete rows possible, you can add .onDelete modifier to the ForEach loop. You cannot apply this modifier to Lists, this is why it is better to use a ForEach loop inside the List.
Accepted Answer
If You want to make delete rows possible, you can add .onDelete modifier to the ForEach loop. You cannot apply this modifier to Lists, this is why it is better to use a ForEach loop inside the List.
Accepted Answer
Another benefit of nesting a ForEach inside a List is the ability to add static elements to the list. Say for example you want to show a button above the list. You could do it like this:

Code Block
struct SwiftUIView: View {
    var items = ["item01", "item02", "item03"]
    var body: some View {
        List {
            Button("Add new item") {
                print("Adding new item")
            }
            ForEach(items, id: \.self) { item in
                Text(item)
            }
        }
    }
}

One more use is that, When u add static elements like button within the List, it wont be updated when view gets invalidated through a @Published property. We need ForEach within the List to get it updated.

  @ObservedObject private(set) var viewModel: SongsViewModel
   
  init() {
    viewModel = SongsViewModel()
  }
   
  var body: some View {
    VStack {
      List {
        ForEach(viewModel.songsList, id:\.self) { song in
          Button(action: {
            viewModel.didSelect(song: song)
          }) {
            FlatTileView(model: song)
              .frame(height: 60)
          }
        }
      }
    }
  }
}

In the above example, ViewModel gets updated when user gives us access to user's Media Library.
If i removed ForEach, the elements within the list will not be updated.

Working of List and ForEach in SwiftUI
 
 
Q