I am trying to create a list of views displayed side by side in an HStack. The views are initialized by a list data structure, myArray.
The current implementation accesses every element of the array, which is not desirable. Is there a stride function available in the new ForEach that allows me to index every other element of the array to initialize the row?
struct MyHStackView: View {
var myArray = [SomeStruct(1), SomeStruct(3), SomeStruct(4), SomeStruct(5), SomeStruct(6)]
var body: some View {
ScrollView(.vertical) {
VStack {
ForEach(myArray.indices.stride(by: 2)) { index in
HStack {
SubView(myArray[index])
SubView(myArray[index+1])
}
}
}
}
No, there is no stride function available in the new ForEach. However, you can achieve the desired behavior by using a combination of stride and enumerated functions on the myArray array, like this:
struct MyHStackView: View {
var myArray = [SomeStruct(1), SomeStruct(3), SomeStruct(4), SomeStruct(5), SomeStruct(6)]
var body: some View {
ScrollView(.vertical) {
VStack {
ForEach(Array(myArray.enumerated()), id: \.offset) { index, element in
if index % 2 == 0 {
HStack {
SubView(element)
if index+1 < myArray.count {
SubView(myArray[index+1])
}
}
}
}
}
}
}
}
This code uses enumerated to get both the index and element of each item in the myArray array. Then, it uses the % operator to check if the index is even, and only creates an HStack with two SubView if the index is even. Finally, it checks if the next index is within the bounds of the array before creating a second SubView. This way, you only access every other element of the array.