问题
I am getting the following error "Closure containing control flow statement cannot be used with function builder 'ViewBuilder'" Not able to find similar troubleshoot anywhere.
struct FavoriteView: View {
@EnvironmentObject var userData: UserData
@State var isfavorite = false
var favoriteindex = [1,2,3]
var body: some View {
NavigationView {
List {
ForEach(userData.labvaluesUserdata) {section in
for numbers in favoriteindex {
if section.id == (numbers) {
ItemRow(list: section)
}
}
}
}
}
}
}
With this I am able to get the first index. Any simple way to loop through ?
List {
ForEach(userData.labvaluesUserdata) { section in
if section.id == self.favoriteindex.first {
ItemRow(list: section)
}
}
}
回答1:
You can do it, and it's simple as that
enum SectionType: Identifiable {
var id: Int {
switch self {
case .first:
return 1
case .second:
return 2
case .third:
return 3
}
}
case first
case second
case third
}
struct UserData {
var labvaluesUserdata: [SectionType] = [.first, .second, .third, .first, .second]
}
struct ItemRow: View {
var list: SectionType
var body: some View {
Text("\(list.id)")
}
}
struct ContentView: View {
@State var userData = UserData()
@State var favoriteindex: [Int] = [2, 3]
var body: some View {
NavigationView {
List {
ForEach(userData.labvaluesUserdata) {section in
if self.favoriteindex.contains(where: { $0 == section.id }) {
ItemRow(list: section)
}
}
}
}
}
}
Updated: added brand new solution. Tried it and it works
来源:https://stackoverflow.com/questions/59074063/swiftui-how-do-i-loop-through-an-array-of-int-inside-for-each