问题描述
我需要增加 genNum 变量并将其传递给ForEach循环中的另一个结构。我的代码正在正确编译,但是无法在模拟以及画布中预览。获取“无法在此文件中预览”。我收到的另一个错误是“ RemoteHumanReadableError:操作无法完成。(BSServiceConnectionErrorDomain错误3。)”。
BSServiceConnectionErrorDomain(3): == BSErrorCodeDescription:OperationFailed
import SwiftUI
@available(iOS 14.0,*)
struct CategoryView: View {
@State var genNum: Int = -1
var categories: [Int: [PokemonData]] {
Dictionary(
grouping: pokemonData,by: { $0.generation }
)
}
var columns: [GridItem] = [
GridItem(.fixed(170)),GridItem(.fixed(170))
]
var body: some View {
NavigationView {
ScrollView {
LazyVGrid(columns: columns) {
ForEach(categories.keys.sorted(),id: \.self) { key in
CategoryCard(genNum: self.increment()) // <--- Having problem with this line
}
}
AllCard()
.padding(.horizontal,15)
.padding(.bottom,20)
}
.navigationTitle("Categories")
}
}
// Function to increment the state value
func increment() -> Int {
self.genNum += 1
let i = genNum
return i
}
}
解决方法
如果您要做的只是将值0到count-1传递给CategoryCard()
初始化程序,则可以使用enumerated()
函数。该函数将一个数组作为输入并返回一个元组数组,其中第一项是数组索引,第二项是原始数组中的元素。
此代码,例如:
let array = ["zero","one","two","three"]
array.enumerated().forEach { (index,string) in
print (index,string)
}
输出以下内容:
0 zero
1 one
2 two
3 three
所以您可以这样重写代码:
LazyVGrid(columns: columns) {
ForEach(categories.keys.sorted().enumerated(),id: \.self) { (index,key) in
CategoryCard(genNum: index) // <--- Having problem with this line
}
}
(免责声明:我还没有使用SwiftUI,所以我对LazyGrid内的ForEach所做的事情还不清楚)