Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SwiftUI中增加ForEach循环中的状态?_Swift_Foreach_Swiftui_State_Increment - Fatal编程技术网

如何在SwiftUI中增加ForEach循环中的状态?

如何在SwiftUI中增加ForEach循环中的状态?,swift,foreach,swiftui,state,increment,Swift,Foreach,Swiftui,State,Increment,我需要增加genNum变量并将其传递给ForEach循环中的另一个结构。我的代码正在正确编译,但无法在模拟和画布中预览它。获取“无法在此文件中预览”。我收到的另一个错误是“RemoteHumanReadableError:操作无法完成。(BSServiceConnectionErrorDomain错误3.) BSServiceConnectionErrorDomain(3): ==BSErrorCodeDescription:操作失败 导入快捷界面 @可用(iOS 14.0,*) 结构类别视图:

我需要增加genNum变量并将其传递给ForEach循环中的另一个结构。我的代码正在正确编译,但无法在模拟和画布中预览它。获取“无法在此文件中预览”。我收到的另一个错误是“RemoteHumanReadableError:操作无法完成。(BSServiceConnectionErrorDomain错误3.)

BSServiceConnectionErrorDomain(3): ==BSErrorCodeDescription:操作失败

导入快捷界面
@可用(iOS 14.0,*)
结构类别视图:视图{
@状态变量genNum:Int=-1
变量类别:[Int:[口袋妖怪]]{
字典(
分组:口袋妖怪,
作者:{$0.0}
)
}
变量列:[GridItem]=[
GridItem(.fixed(170)),
网格项(.fixed(170))
]
var body:一些观点{
导航视图{
滚动视图{
LazyVGrid(列:列){
ForEach(categories.keys.sorted(),id:\.self){输入
CategoryCard(genNum:self.increment())//Int{
self.genNum+=1
设i=genNum
返回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
                }
            }
LazyVGrid(列:列){
中的ForEach(categories.keys.sorted().enumerated(),id:\.self){(index,key)

CategoryCard(genNum:index)//为什么在视图呈现阶段需要它?在ForEach循环行中获取此错误:1.泛型结构“ForEach”要求“EnumeratedSequence”(又名“EnumeratedSequence”)符合“RandomAccessCollection”2.类型“EnumeratedSequence.Element”(又名“偏移量:Int,元素:Int)”)无法符合“Hashable”;只有结构/枚举/类类型可以符合协议
            LazyVGrid(columns: columns) {
                
                ForEach(categories.keys.sorted().enumerated(), id: \.self) { (index, key) in
                    CategoryCard(genNum: index) // <--- Having problem with this line
                }
            }