The ForEach struct in swiftUI is really useful for iterating over an array to create views, but I'm wondering if there is a way to iterate over multiple arrays at the same time. I know that if you use zip when you are using a for in loop you can achieve this like:
for (height, label) in zip(heights, labels) {
print("\(height) : \(label)")}
However, i'm wondering if it's possible to do this with a ForEach. I have tried, but I can't seem to get it right. The only way i've found to iterate over two arrays is to use an index to subscript each array, but that doesn't seem swifty enough.
What i've tried so far is:
let heights:[CGFloat] = [20, 40, 100, 5, 70, 80, 30]
let labels = ["mon", "tue", "wed", "thu", "fri", "sat", "sun", ]
ForEach(zip(heights, labels), id: \.self) { (height, label) in
Text("\(height)")
Text(label)
}
But no joy, and the swiftUI errors are as cryptic as ever..... Any pointers gratefully received.
Edit: One way of getting it working that I have found is to do a nested ForEach, like:
ForEach(self.heights, id: \.self) { height in
Group {
Text("\(height)")
ForEach(self.labels, id: \.self) { label in
Text(label)
}
}
}
But again, it doesn't seem very swifty.
Here is possible approach (tested & worked with Xcode 11.3.1)
ForEach(Array(zip(heights, labels)), id: \.0) { item in
VStack {
Text("\(item.0)")
Text(item.1)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With