aturan23
aturan23

Reputation: 5410

SwiftUI ForEach array indices not rendering

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

Upvotes: 3

Views: 1153

Answers (1)

Asperi
Asperi

Reputation: 258443

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
          }
        }
      }
    }
  }
}

Upvotes: 4

Related Questions