Home > Software design >  ForEach within List: Benefit of the pattern?
ForEach within List: Benefit of the pattern?

Time:01-17

For example:

List {
    ForEach(model) { elem in 
        /* ... */
    }
}

Why is a ForEach wrapped within a List? What's the benefit of that pattern?

Why not using List(model) { ... } alone and no ForEach at all?

CodePudding user response:

A ForEach loop wrapped within a List is typically used when displaying a list of items in a SwiftUI view. The List initializer creates a scrolling container for the items, while the ForEach loop iterates over the items and creates a new view for each one. This pattern allows for efficient and dynamic updates to the list, as SwiftUI can automatically diff the old and new list and determine which views need to be updated or removed.

If you use List(model) { ... } alone and no ForEach at all , it will only take one single item and it will not iterate over the list.

CodePudding user response:

You can have some non-repeating elements before and after the ForEach but keeping them inside the list, so you can use list functionalities like edit, delete, swipe, reorder, row style and etc on them.

  • Related