繁体   English   中英

SwiftUI:如何循环遍历“For Each”中的 Int 数组

[英]SwiftUI: How do I loop through an array of Int inside "For Each"

我收到以下错误“包含控制流语句的闭包不能与函数构建器‘ViewBuilder’一起使用”无法在任何地方找到类似的故障排除。

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)
                   }
                }
            }
         }
      }
   }
}

有了这个,我就可以获得第一个索引。 任何简单的循环方法?

List {
   ForEach(userData.labvaluesUserdata) { section in
      if section.id == self.favoriteindex.first {
         ItemRow(list: section)
      }
   }
}

你可以做到,就这么简单

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)
                    }
                }
            }
        }
    }
}

更新:添加了全新的解决方案。 试过了,有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM