Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI ForEach index jump by 2

I am working on SwiftUI ForEach. Blow image shows what I want to achieve. For this purpose I need next two elements of array in single iteration, so that I can show two card in single go. I search on a lot but did find any way to jump index swiftUI ForEach.

need to show two cards in single iteration

Here is my code in which I have added the element same array for both card which needs to be in sequence.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    ScrollView(.vertical, showsIndicators: false) {
                VStack(spacing: 0) {
                    // I need jump of 2 indexes
                    ForEach(videos) { video in
// need to show the next two elements of the videos array
                        HStack {
                            videoCardView(video: video)
                            Spacer()
                            // video + 1
                            videoCardView(video: video)
                        }
                        .padding([.leading, .trailing], 30)
                        .padding([.top, .bottom], 10)

                    }
                }
            }
            .background(Color(ColorName.appBlack.rawValue))
        }

Any better suggestion how to build this view.

>Solution :

While LazyVGrid is probably the best solution for what you want to accomplish, it doesn’t actually answer your question.

To "jump" an index is usually referred to as "stepping" in many programming languages, and in Swift it’s called "striding".

You can stride (jump) an array by 2 like this:

ForEach(Array(stride(from: 0, to: array.count, by: 2)), id: \.self) { index in
    // ...
}

You can learn more by taking a look at the Strideable protocol.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading