Search code examples
swiftforeachpicker

How to pick a specific range in a ForEach loop for swift


I hope this is not a really dumb question, but I can't seem to figure it out. I have an array with many entries and I would like to display a certain range of options in a picker (lets say from then 2nd item in the array to the 5th). Ive done this with a ForEach loop but I can't figure out how to specify the exact range of the loop to run. This is a sample code below that runs but displays the whole array. Thank you for your help

import SwiftUI

struct Plans: Identifiable {
    var id = UUID()
    var plan1: String
    var plan2: String
    var plan3: String
}

struct ContentView: View {
    @State private var picked = ""
    
    let goals = [
        Plans(plan1: "A", plan2: "B", plan3: "C"),
        Plans(plan1: "D", plan2: "D", plan3: "F"),
        Plans(plan1: "F", plan2: "G", plan3: "H"),
        Plans(plan1: "I", plan2: "J", plan3: "K"),
        Plans(plan1: "L", plan2: "M", plan3: "N"),
        Plans(plan1: "o", plan2: "P", plan3: "Q"),
        Plans(plan1: "R", plan2: "S", plan3: "T"),
        Plans(plan1: "U", plan2: "V", plan3: "W"),
        Plans(plan1: "X", plan2: "Y", plan3: "Z")
    ]
    
    
    var body: some View {
        NavigationView {
            Form {
                Picker(selection: self.$picked, label: Text("Pick your plan")) {
                    ForEach(goals, id:\.plan1)  { goal in
                        Text("\(goal.plan1)").tag(goal.plan1)
                    }
        
                }.id(UUID())
            }
        }
    }
}

Solution

  • You can do:

    ForEach(2..<goals.count, id: \.plan1) { goal in
        Text("\(goals[goal].plan1)")
            .tag(goals[goal])
    }
    

    This is how you do it in swiftui. For-in loops are not allowed in ViewBuilders.

    i.e. for i in 2...5 will not work in swiftUI views, but this will:

    ForEach(2...5, id: \.self) { goal in
        ...
    }