如何在ForEach循环中获取项目的索引?

时间:2019-10-29 21:55:42

标签: ios arrays swift foreach swiftui

我有一个遍历数组的数组。该数组的结构代表一年的四个季度:

Q0 1月,2月,3月
Q1四月,五月,六月
Q2七月,八月,九月
10月3日,12月11日

@State var quarters: [[Month]] = [[.init(name: "January"),.init(name: "February"),.init(name: "March")],
                               [.init(name: "April"), .init(name: "May"), .init(name: "June")],
                               [.init(name: "July"),.init(name: "August"),.init(name: "September")],
                               [.init(name: "October"), .init(name: "November"), .init(name: "December")]]

在下面的HStack中,我试图附加索引quarter,以便最终得到Q0,Q1,Q2,Q3

VStack {

    ForEach (self.quarters, id: \.self) { quarter in
        VStack {
        Spacer()
            HStack {

                Text("Q\(quarter.index)")
                .font(.system(size: 40, weight: .black, design: .rounded))

            }
        }
    }
}

这没有用。有没有办法在这里获取我的ForEach循环的数组内的数组索引?我知道,如果ForEach循环使用范围作为其数据集,则有一种方法可以检索索引,但是如果数据集是数组,则不可以。

2 个答案:

答案 0 :(得分:1)

您可以使用枚举数组进行这种操作:

   struct TempView: View{

   @State var quarters: [[Month]] = [[.init(name: "January", products: ["1", "2"]),.init(name: "February", products: ["1", "2"]),.init(name: "March", products: ["1", "2"])],
[.init(name: "April", products: ["1", "2"]), .init(name: "May", products: ["1", "2"]), .init(name: "June", products: ["1", "2"])]]

  var body: some View {

        ForEach (self.quarters.indices , id: \.self) { (index) in

        VStack {
        Spacer()
            HStack {
                Text("Q\(index)")
                .font(.system(size: 40, weight: .black, design: .rounded))
                Button("TestButton",action: {
                    self.quarters.append([.init(name: "January", products: ["1", "2"]),.init(name: "February", products: ["1", "2"]),.init(name: "March", products: ["1", "2"])])
                })
            }
             Spacer()
        }
    }

 }}                                                                                                

答案 1 :(得分:0)

一种解决方法是查找数组中元素的位置

Text("Q\(self.quarters.firstIndex(of: quarter)!)")