SwiftUI: How do I loop through an array of Int inside “For Each”

允我心安 提交于 2020-01-24 19:25:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!