Your Variable
class contains a property called items
that is an array of Variables
structs.
The variable
property in the View
named Introduction
is an instance of the Variable
class, meaning it has a property called items
that is an array of Variables
structs.
Each item in an array has an index, starting at 0
for the first item. So the first Variables
struct inside the items
array of the variable
property can be accessed as variable.items[0]
.
Once you have that item, you can then access its properties: id
, allTime
or introduction
.
So you essentially have this structure:
Variable
|- items
|- 0: Variables
|- id
|- allTime
|- introduction
|- 1: Variables
|- id
|- allTime
|- introduction
|- etc etc
Clear?
Okay, so let's say you want to show a Text
element that displays the introduction
property of the first item in the items
array. Here's how you would do that:
struct Introduction: View {
@StateObject var variable = Variable()
@StateObject var tempVars = tempVariables()
var body: some View {
Text(variable.items[0].introduction) //remember, arrays start at index 0
}
}
If you wanted to show the introduction
from the 2nd item in the array, you would use Text(variable.items[1].introduction)
. If you wanted to show the value of allTime
from the 1st item in the array, you would use Text(variable.items[0].allTime)
, and so on.
You are getting an out of index error when calling variable.items[3]
because you apparently don't have 4 (remember indexes are 0-based!) items in the array.
I would strongly suggest renaming your data structures and variables to make it clearer what things are and how they are to be used. Variable
and variable
just are not very descriptive names. You will end up reading your code far more than you write it, so it is always a good idea to name things so that they will be understandable to you when you come back to read something you wrote before. Also so that other people reading your code can understand it better.
So, for instance, Variable
. What does that mean in the context of this data structure? It contains ann array called items
; maybe something like ItemStore
would be a better name than Variable
. Even that is a too generic, but I don't know your codebase like you do so it's hard to suggest something more specific.
It's also confusing when you have a class called Variable
and a struct called Variables
. I had to go back and edit this answer because I got confused which was which. Plus, in Swift, the convention is to name a data type in the singular and then name an array of those types as a plural. So you would have a class called, e.g., ThingStore
, a struct called Thing
and a variable holding an array of Thing
s called things
. (But don't actually use Thing
, etc. That's just as bad as Variable
. I just wanted to demonstrate the pattern.)