2

I came to SwiftUI from UIKit world and wondered how lists work in SwiftUI. This topic is a continuation of the topic about ForEach.

The question is how to make sure that the list of elements is effective in terms of memory management and speed.

So I came up with two different implementations:

  1. List of cells based on List:
List {
    ForEach(0..<469) { i in
        MyCellView(num: i)
            .frame(height: 40)
    }
}
  1. List of cells based on VStack:
ScrollView {
    VStack {
        ForEach(0..<469) { i in
            MyCellView(num: i)
                .frame(height: 40)
        }
    }
}
  1. List of cells based on LazyVStack:
ScrollView {
    LazyVStack {
        ForEach(0..<469) { i in
            MyCellView(num: i)
                .frame(height: 40)
        }
    }
}

Seems like ForEach acts like a generator which supply the parent view with new items. In the example 2 with VStack, the memory graph shows a lot of pre-defined structures (as expected 469 in my case):

VStack with ForEach in SwiftUI

Does it means that they are pre-rendered or just structures in memory?

In opposite to 2, examples 1 and 3 are requesting only the number of cells which is displayed on the screen.

But still, the main questions is how to make sure that SwiftUI reuses the cells as UITableView did and avoid memory overflow?

Timmy
  • 4,098
  • 2
  • 14
  • 34
mazy
  • 652
  • 1
  • 10
  • 18
  • In LazyVStack there is Lazy : that means the system try to render only the needed views (which are structs). The List seems to act quite the same (even if not directly stated as this in doc ) The VStack will need to render all its contents. – Ptit Xav Oct 07 '22 at 10:27

0 Answers0