I'm trying to access the second value in a published array of CGFloats, and I keep getting the "index out of range" error. In the code below I've given two examples, the first works with a test array of CGFloats, where the Text position works for both xy values. The second ForEach array highlights the problem I'm having where I can only write out the wrapped first value or index [0] but the second value keeps giving me this error.
I'm flummoxed!
class A: ObservableObject{
@Published var pp: [[CGFloat]] = [[0]]
}
struct ContentView: View {
@ObservedObject var a = A()
func updateP(){
var xyvalues = [[56.833333333333336, 153.75], [23.833333333333332, 137.35], [209.0, 229.6], [306.1666666666667, 192.7]]
for pp in xyvalues{
print(pp)
a.pp.append([pp[0],pp[1]])
}
}
init() {
updateP()
}
var array: [[CGFloat]] = [[2,3],[40,50],[200,200]]
var body: some View {
ZStack{
ForEach(Array(zip(array.indices, array)), id: \.0) { i, a in
Text(a[1].description)
.position(x: a[0], y: a[1])
}
ForEach(Array(zip($a.pp.indices, $a.pp)), id: \.0) { i, p in
Text(p.wrappedValue.description)
.position(x: p.wrappedValue[0], y: p.wrappedValue[0])
Text(p.wrappedValue.description)
.position(x: p.wrappedValue[0], y: p.wrappedValue[1])
}
}
}
}
The problem is in the initialisation of your @Published var pp: [[CGFloat]] = [[0]]
, because this is initialising pp with a single 0 value - to which you append tuples in updateP. Changing it to @Published var pp = [[CGFloat]]()
fixes the problem.
If you want to start with [0,0], then change the initialisation of pp to be @Published var pp: [[CGFloat]] = [[0,0]]
Best wishes and regards, Michaela