Does SwiftUI LazyHStack / LazyVStack still work if the ForEach loop nested?

Viewed 1038

This is my code

LazyHStack(spacing: spacing) {
   InnerView(data: self.data) // The for loop is contained inside the InnerView
}

LazyHStack(spacing: spacing) {
   ForEach(data, id: \.self) { viewDataMap in
       buildView(viewDataMap: viewDataMap)
   }
}

Does the "Lazyness" work for both code segments?

2 Answers

It works, but Previews crash on Xcode 12.4 (12D4e)

Reported to feedbackassistant

FB9121009 (Previews crash if LazyVStack contains two nested ForEach where Data.Element : Identifiable)

import Foundation
import SwiftUI

struct NestedForEachInLazyVStack: View {

    var items1 = (0..<3).map { _ in Item() }
    var items2 = (0..<3).map { _ in Item() }

    @ViewBuilder
    var body: some View {
        if #available(iOS 14.0, *) {
            LazyVStack {
                ForEach(items1) { _ in
                    ForEach(items2) { _ in
                        Text("text")
                    }
                }
            }
        }
    }
}

struct Item: Identifiable {
    var id = UUID()
}

struct NestedForEachInLazyVStack_Previews: PreviewProvider {
    static var previews: some View {
        NestedForEachInLazyVStack()
    }
}

Yes, it should work as you expected. The Lazy property takes effect only when you have more items than your screen can show. If the number of items you have in your view fits in your screen, it doesn't have sense to use Lazy stacks.

Related