3

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

1 Answer 1

4

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
          }
        }
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.