Search code examples
arraysswiftuistructforeachfunc

SwiftUI: Where to Populate Arrays?


A naive question that I'll ask naively. If I have an array:

var testArray    = [Double](repeating: 0.0, count: 100)

And want to populate it, in this instance with some dummy data:

func populateTestArray() {
    ForEach((0 ..< testArray.count), id: \.self) { index in
        testArray[index] = Double.random(in: 1...100)
    }
}

Where, and how, do I do so?

The compiler, quite understandably, says that testArray is not in the scope. What is the approved way of doing this in a .swift? I don't want to have to resort to Global Variables as this data isn't.

I have tried defining the variable with @State and with a .onAppear in the var body: some View { but again the compiler says "no".

ForEach((0 ..< testArray.count), id: \.self) { index in
            testArray[index] = Double.random(in: 1...100)           
}.onAppear

What is the approved approach?


Solution

  • You need to read and learn the basics of SwiftUI first, then code something, see for example: https://developer.apple.com/tutorials/swiftui/

    Try this:

    struct ContentView: View {
        @State var testArray: [Double] = [] // <-- empty array declaration
        
        var body: some View {
            ScrollView {
                ForEach(testArray.indices, id: \.self) { index in
                    Text("\(testArray[index])")
                }
            }
            .onAppear {
                // --- "normal" code here, or in functions
                // add 100 random numbers to the array
                for _ in 0..<100 {
                    testArray.append(Double.random(in: 1...10))
                }
            }
        }
    }
    

    You could also do this:

    struct ContentView: View {
        @State var testArray: [Double] = (1...100).map{ _ in Double.random(in: 1...100) }
        
        var body: some View {
            ScrollView {
                ForEach((0 ..< testArray.count), id: \.self) { index in
                    Text("\(testArray[index])")
                }
            }
        }
    }
    

    Note, you use ForEach in/with Views, and swift for i in range { } in functions.