SwiftUI:如何在 "For Each" 中循环遍历 Int 数组
SwiftUI: How do I loop through an array of Int inside "For Each"
我收到以下错误 "Closure containing control flow statement cannot be used with function builder '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: { [=10=] == section.id }) {
ItemRow(list: section)
}
}
}
}
}
}
更新:添加了全新的解决方案。试过了,有效
我收到以下错误 "Closure containing control flow statement cannot be used with function builder '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: { [=10=] == section.id }) {
ItemRow(list: section)
}
}
}
}
}
}
更新:添加了全新的解决方案。试过了,有效