首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >SwiftUI:如何循环遍历“每个”内部的Int数组

SwiftUI:如何循环遍历“每个”内部的Int数组
EN

Stack Overflow用户
提问于 2019-11-27 07:58:09
回答 1查看 3.1K关注 0票数 2

我得到以下错误“包含控制流语句的闭包不能与函数生成器‘ViewBuilder’一起使用”无法在任何地方找到类似的疑难解答。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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)
                   }
                }
            }
         }
      }
   }
}

有了这个,我就能得到第一个索引。有什么简单的方法可以通过吗?

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
List {
   ForEach(userData.labvaluesUserdata) { section in
      if section.id == self.favoriteindex.first {
         ItemRow(list: section)
      }
   }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-27 14:57:31

你能做到的,就这么简单

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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)
                    }
                }
            }
        }
    }
}

更新:新增全新解决方案。试过了,它可以工作,

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59074063

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文