Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI ForEach array indices not rendering

Tags:

swift

swiftui

I have a simple view:

struct SomeView: View {
  @ObservedObject var viewModel: ViewModel()
  var body: some View {
    GeometryReader { fullView in
      ScrollView {
        VStack(spacing: 40) {
          ForEach(self.viewModel.list) { item in
            Text(item.name)
          }
        }
      }
    }
  }
}

This is working. But I need work with index. And I tried to change my ForEach loop:

ForEach(self.viewModel.list.indices) { index in
  Text(self.viewModel.list[index].name)
}

But this time ForEach does not render anything. But on console written:

ForEach<Range<Int>, Int, ModifiedContent<ModifiedContent<GeometryReader<ModifiedContent<ModifiedContent<ModifiedContent<...>, _FrameLayout>, _TransactionModifier>> count (10) != its initial count (0). `ForEach(_:content:)` should only be used for *constant* data. Instead conform data to `Identifiable` or use `ForEach(_:id:content:)` and provide an explicit `id`!

My model is Identifiable

like image 442
aturan23 Avatar asked Apr 12 '26 17:04

aturan23


1 Answers

You can have both, like in below

struct SomeView: View {
  @ObservedObject var viewModel: ViewModel()
  var body: some View {
    GeometryReader { fullView in
      ScrollView {
        VStack(spacing: 40) {
          ForEach(Array(self.viewModel.list.enumerated()), id: \.1) { index, item in
            Text(item.name)
            // ... use index here as needed
          }
        }
      }
    }
  }
}
like image 117
Asperi Avatar answered Apr 15 '26 19:04

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!