swiftfor-loopswiftuiswiftui-list

SwiftUi : for i in 0... How to solve closure containing control flow statement


I want to display some images that depend on an integer.

Example with '3':

enter image description here

VStack {
     Text(recette.name)
     HStack() {
           Text("Durée 20 min")
             .font(.caption)
             .fontWeight(.light)
           Text("Notes")
             .font(.caption)
             .fontWeight(.light)
           HStack(spacing: -1.0) {
                for 0 in 0...recette.avis{
                      Image(systemName: "star.fill")
                        .padding(.leading)
                        .imageScale(.small)
                        .foregroundColor(.yellow)
                 }
            }
     }
}

but the code doesn't compile with this error in for.

Closure containing control flow statement cannot be used with function builder 'ViewBuilder'


Solution

  • You want to use a ForEach so that you can create your stars.

    Below is a working example.

    // This is a simple struct to mock the data
    struct Recette {
        let name: String = "Test"
        let avis: Int = 3
    }
    
    struct ContentView: View {
    
        let recette = Recette()
    
        var body: some View {
            VStack {
                Text(recette.name)
                HStack() {
                    Text("Durée 20 min")
                        .font(.caption)
                        .fontWeight(.light)
                    Text("Notes")
                        .font(.caption)
                        .fontWeight(.light)
                    HStack(spacing: -1.0) {
                        ForEach(0..<recette.avis) {_ in // <- use ForEach() here
                            Image(systemName: "star.fill")
                                .padding(.leading)
                                .imageScale(.small)
                                .foregroundColor(.yellow)
                        }
    
                    }
                }
            }
        }
    }
    

    This is what the above code produces:

    What code produces