How to address elements in an EnvironmentObject Array

I am new to programing apps, and I am trying to figure out how to use one item out of an array of items in a Text line. I am not getting any complaints from Xcode, but then the preview crashes giving me a huge error report that it keeps sending to Apple. I have cut out all the extra stuff from the app to get just the basics. What I want it to print on the screed is "Hello Bill How are you?" with Bill being from the observable array. The first picture below is about 2 seconds after I removed the // from in front of the line that reads Text("(friend2.friend2[1].name)"). The other two pictures are the main app page and the page where I setup the array. At the very bottom is a text file of the huge report it kept sending to Apple, until I turned of the option of sending to Apple. Would someone please explain what I am doing wrong. Well a side from probably everything.

Replies

Problem probably comes from the absence of environment var in Preview.

Try this:

#Preview {
  ContentView()
            .environmentObject(Friends()) 
}

Or

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(Friends())  // Essential, to connect to environment
    }
}

Why do you call ContentView in the Preview of SharedVariableTestApp:

Your naming conventions do not help.

  • Why have a property friend2 (not very explicit) having the same name as the var ? It does not help reading your code.
  • struct frie : does it stand for Friend (and it should start with Uppercase)

If that works, don't forget to close the thread by marking the correct answer. Otherwise, explain the problem and please, post the actual code, not screenshots.

  • Thank you very much. It is working now.

    Yes I do need to work on more creative variable names. I have gotten better, back when I was using Fortran I used A, B, C, D, etc for my variables.

Add a Comment