Home > front end >  Why can I list an array with List, but not with a For Loop and Text?
Why can I list an array with List, but not with a For Loop and Text?

Time:10-26

The error is: "Closure containing control flow statement cannot be used with result builder 'ViewBuilder'"

This code here works...

            if let a = array {
                List(a, id: \.self) { item in
                    Text(item)
                }
            } else {
                Text("Please click add button.")
            }

But this code here (which is found in the block of code at the bottom) does not? How come?

                if let a = array {
                    for element in 0...a.count-1 {
                        Text(a[element])
                    }
                } else {
                    Text("Please click add button.")
                }

Source code...

@State var array:[String]? = nil
    @State var message = ""
    
    var body: some View {
        VStack {
            Text(message)
                .font(.body)
            HStack {
                Button("Set to nill") {
                    array = nil
                }.padding()
                Button("Add strings") {
                    array = ["String 1", "String 2", "String 3"]
                }.padding()
            }
            //Why doesn't the below work?
            if let a = array {
                for element in 0...a.count-1 {
                    Text(a[element])
                }
            } else {
                Text("Please click add button.")
            }
        }
    }
}

CodePudding user response:

All of the SwifUI view builders are building structures. When you create such a struct in your for loop, that struct is deleted when it goes out of scope in the loop.

SwiftUI uses things like ForEach and List to stand in for flow control structures like for but still create nested structures.

  • Related