-2

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?

Edward Hasted
  • 3,201
  • 8
  • 30
  • 48
  • "In UIKit this was simplistic" is fortunately a personal viewpoint that you'll be able to move past. There's not really a different answer for SwiftUI—just more options that will suit your needs based on different situations. Why do you think that UIKit didn't use `.swift` files? Have you only moved to Swift for SwiftUI, previously only using Objective-C? –  Jan 12 '23 at 12:03
  • I will edit that comment out if it offends. What I was trying to say was that dealing with arrays was a lot easier in the UIKit and populating them in SwiftUI is confounding me. Hence the reason for reaching out for some help and coding therapy. – Edward Hasted Jan 12 '23 at 12:07

1 Answers1

1

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.