SwiftUI:如何循环遍历“ For Each”内部的Int数组 [英] SwiftUI: How do I loop through an array of Int inside "For Each"
本文介绍了SwiftUI:如何循环遍历“ For Each”内部的Int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到以下错误消息:包含封闭流的控制流语句无法与函数构建器 ViewBuilder一起使用。
无法在任何地方找到类似的故障排除方法。
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)
}
}
}
推荐答案
您可以做到,而且很简单
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)
}
}
}
}
}
}
已更新:已添加全新解。尝试了一下,就可以了
这篇关于SwiftUI:如何循环遍历“ For Each”内部的Int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文