Why ForEach cannot include extra logic?

Hi! I am trying to add some logic in ForEach to compute the views, but XCode does not allow that. Can you tell me why?


ForEach(0...10, id: \.self, content: {
 i in                   
 let s : Int = i
 return Text("abc")
}


XCode will return error message for the above coce: Cannot convert value of type '(_) -> _' to expected argument type '(_.Element) -> _'


However, the code below will work:

ForEach(0...10, id: \.self, content: {
i in                  
return Text("abc")
}


I looked at the declaration of ForEach, but couldn't find why it doesn't accept the "let" statement.

init(_ data: Data, @ViewBuilder content: @escaping (Data.Element) -> Content)


I understand that if I put the logic in a separate structure view for each cell, I can get the code work, but just trying to get a better understanding on SwiftUI and posted this question.


Thank you!

Answered by Claude31 in 399955022

This will work:


struct ContentView: View {
   
    var body: some View {
        List {
            ForEach(0...200, id: \.self) { i -> Text in
                let s : Int = i*i
                return Text("Text \(s)")
            }
        }
    }
}


Now, closure knows what to return (Text)


Without the let declaration, compiler can infer the type from a single line.

Of course, in this case you can even write simpler form without return. Everything is implicit


            ForEach(0...200, id: \.self) { _ in
                Text("abc")
            }
Accepted Answer

This will work:


struct ContentView: View {
   
    var body: some View {
        List {
            ForEach(0...200, id: \.self) { i -> Text in
                let s : Int = i*i
                return Text("Text \(s)")
            }
        }
    }
}


Now, closure knows what to return (Text)


Without the let declaration, compiler can infer the type from a single line.

Of course, in this case you can even write simpler form without return. Everything is implicit


            ForEach(0...200, id: \.self) { _ in
                Text("abc")
            }

Did it work for you ? Thanks to report and close the thread.

Thank you Claude31!
Why ForEach cannot include extra logic?
 
 
Q