Randomizing a ForEach view loop

Hello! I am trying to make a list of numbers where when I press a button, random numbers show up, and each time you press it the button, it changes. I have code that I think should accomplish this but I am very confused about how it works. When I use $Array.index(Int, offSetBy: 0), does this return the value at that place in the array, or does that just return the Int I put into it? Anyway, here's my code, hopefully someone can help me. Thanks!

import SwiftUI

struct ContentView: View {
   
  @State var numm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
   
  @State var fill = 0
   
  var body: some View {
    VStack{
      Button {
        fill = 0
        numm.removeAll()
         
        while fill < 20 {
          numm.append(Int.random(in: 0...1))
          fill += 1
        }
      } label: {
        Text("Make List")
      }

      ForEach(1...(20), id: \.self) { box in
        if $numm.index(box.self, offsetBy: 0) == 1 {
          Text("\(box.self)")
        }
        else {
          Text("----")
        }
      }
    }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

Here is what this code do

      ForEach(1...20, id: \.self) { box in
        if $numm.index(box.self, offsetBy: 0) == 1 {
          Text("\(box.self)")
        }
        else {
          Text("----")
        }
  • box will be Int from 1 to 20 (no need to enclose 20 in parentheses).
  • you offset by 0, so the index you get in $numm.index is just box.self
  • And you print only for the first box in ForEach.

What do you want ?

  • a list of 20 items, random 0 or 1 ?
  • I do not understand what you want to achieve with the test on numm.index

Here is a different code, is it what you are looking for ?

struct ContentView: View {
   
  @State var numm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
   
//  @State var fill = 0  // NO NEED for a State var
   
  var body: some View {
    VStack {
      Button {
        var fill = 0  // A local var is enough
        numm.removeAll()
         
        while fill < 20 {
          numm.append(Int.random(in: 0...1))
          fill += 1
        }
      } label: {
        Text("Make List")
      }

      ForEach(1...20, id: \.self) { box in
        if $numm.index(box.self, offsetBy: 0) <= 20 { //I propose to display all items  In fact this test is useless, or is equivalent to `if box <= 20`
          Text("\(box.self) -> \(numm[box])")
        }
        else {
          Text("----")
        }
      }
    }
  }
}
Randomizing a ForEach view loop
 
 
Q