I'm writing my first Swift app and I am looking for some guidance on how best to fill my Text view elements with variables.
Below, I have a simplified version of my app's main ContentView- in reality, it has about 100 Text view elements. I need to change the Text's title to the values Variable1, Variable2, Variable3 and Variable4. With 100 Text view elements, I would have to modify each Text view element to define and use Variable1, Variable 2,......Variable100 (a lot of typing and hard to edit!)
struct TenView: View {
var body: some View {
VStack {
HStack {
VStack {
Text("Group100")
Text("One")
Text("Two")
Text(Variable1)
.background(Color.yellow)
Text("Four")
Text("Five")
Text("Six")
}
VStack {
Text("Group200")
Text("One")
Text("Two")
Text("Three")
Text("Four")
Text(Variable2)
.background(Color.yellow)
Text("Six")
}
VStack {
Text("Group300")
Text("One")
Text(Variable3)
.background(Color.yellow)
Text("Three")
Text("Four")
Text("Five")
Text(Variable4)
.background(Color.yellow)
}
}
}
}
}
Are there better ways to achieve this?
Should I put the 100 Variables into an array and do something like:
myArray: String= ["","Alpha", "Bravo",....."100Zulu"]
VStack {
Text("Group100")
Text("One")
Text("Two")
Text(myArray[1])
.background(Color.yellow)
Text("Four")
Text("Five")
Text("Six")
}
VStack {
Text("Group200")
Text("One")
Text("Two")
Text("Three")
Text("Four")
Text("myArray[2]")
.background(Color.yellow)
Text("Six")
}
Or is there some way of using a forEach with some logic?
VStack {
myArray.forEach { but only in specific Text views
Text($0)
}
}