'Swift UI tutorial ERROR "Closure containing control flow statement cannot be used with function builder 'ViewBuilder'"
I tried swiftUI tutorial "Handling User Input".
https://developer.apple.com/tutorials/swiftui/handling-user-input
Implementing with ”For" instead of "For Each". But error arise "Closure containing control flow statement cannot be used with function builder 'ViewBuilder'".
How I do this?
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"))
}
}
}
Solution 1:[1]
The ForEach confirms to View, so at its core, it is a View just like a TextField. ForEach Relationships
You can't use a normal for-in because the ViewBuilder doesn't understand what is an imperative for-loop. The ViewBuilder can understand other control flow like if, if-else or if let using buildEither(first:), buildEither(second:), and buildif(_:) respectively.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hamza Jadid |
