I tried a SwiftUI tutorial, "Handling User Input".
https://developer.apple.com/tutorials/swiftui/handling-user-input
I tried implementing it with for
instead of ForEach
.
But an error arose: "Closure containing control flow statement cannot be used with function builder 'ViewBuilder'".
FROM:
import SwiftUI
struct LandmarkList: View {
@State var showFavoritesOnly = true
var body: some View {
NavigationView{
List{
Toggle(isOn: $showFavoritesOnly){
Text("Show FavatiteOnly")
}
ForEach(landmarkData) { landmark in
if !self.showFavoritesOnly || landmark.isFavorite {
NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
}
TO (I wrote):
import SwiftUI
struct LandmarkList: View {
@State var showFavoritesOnly = true
var body: some View {
NavigationView{
List{
Toggle(isOn: $showFavoritesOnly){
Text("Show FavatiteOnly")
}
for landmark in landmarkData {
if $showFavoritesOnly || landmark.isFavorite {
NavigationLink(destination: LandmarkDetail(landmark: landmark)){
LandmarkRow(landmark: landmark)}
}
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
}
ForEach
is a special view, butfor
is control flow statement which is not allowed in ViewBuilder where you try to put it in. – Transgressionfor
? TheForEach
view exists precisely because a regularfor
loop can't be used within a view builder function. But there really isn't anything you could do with afor
loop that you can't do withForEach
, so knowing what you want to achieve would help us answer your question. – Iquique