TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Using ForEach

Forums > SwiftUI

I have created some structs to represent a student, an instruction (that a student would take) and an array of student.

I would like to use ForEach to list the instructions for each student but am struggling with a solution.

Any insights would be appreciated.

struct Student: Identifiable {
    var id = UUID()
    var name = ""
    var instructions = [Instruction]()
}

struct Instruction {
    var name = ""
}

struct Students  {
    var id = UUID()
    var people = [Student]()
}

struct ContentView: View {
    @State private var students = Students(id: UUID(), people: [Student(id: UUID(), name: "Joe", instructions: [Instruction(name: "English"), Instruction(name: "Math")]), Student(id: UUID(), name: "Sam", instructions: [Instruction(name: "Science"), Instruction(name: "Economics")])])

    var body: some View {
        List {
            // Would like to use ForEach here to list the instructions for each student here...
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }

}

3      

I think you don't really need to use Students struct for this purpose.

struct Student: Identifiable {
    var id = UUID()
    var name = ""
    var instructions: [Instruction]
}

struct Instruction: Identifiable {
    var id = UUID()
    var name = ""
}

struct ContentView: View {
    @State private var students = [
        Student(name: "Student One", instructions: [Instruction(name: "English"), Instruction(name: "Math")]),
        Student(name: "Student Two", instructions: [Instruction(name: "Science"), Instruction(name: "Economics")])
    ]

    var body: some View {
        NavigationStack {
            List {
                ForEach(students) { student in
                    NavigationLink {
                        List(student.instructions) { instruction in
                            Text(instruction.name)
                        }
                    } label: {
                        Text(student.name)
                    }

                }
            }
        }
    }
}

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.