1

I want to use a ForEach loop, but it doesn't work.

let navigation = [["Kunde", "person"], ["Wartung", "gear"]]


NavigationView {
    List {
        NavigationLink(destination: ListView(title: "Kunde")) {
            Label("Kunde", systemImage: "person")
        }
        NavigationLink(destination: ListView(title: "Wartung")) {
            Label("Wartung", systemImage: "gear")
        }
        // MANY MORE
    }
}

My approach prints the numbers from 0 to 7, but I want the contents of the array.

My approach:

let navigation = [["Kunde", "person"], ["Wartung", "gear"]]


NavigationView {
    List {
        ForEach(navigation.indices) { index in
            NavigationLink(destination: ListView(title: "\(index)")) {
                Label("\(self.index)", systemImage: "\(index)")
            }
        }
    }
}

1 Answer 1

2

You are only giving the index. You could do navigation[index][0] for example to get the title, but this is quite tedious.

A better way is to create a custom type, plus it will also be Identifiable so it's safer to use on a mutating list of items.

Code:

struct ContentView: View {
    private let navigation = [
        NavigatableView("Kunde", image: "person"),
        NavigatableView("Wartung", image: "gear")
    ]

    var body: some View {
        NavigationView {
            List {
                ForEach(navigation) { newView in
                    NavigationLink(destination: ListView(title: newView.title)) {
                        Label(newView.title, systemImage: newView.image)
                    }
                }
            }
        }
    }
}
struct NavigatableView: Identifiable {
    let id = UUID()
    let title: String
    let image: String

    init(_ title: String, image: String) {
        self.title = title
        self.image = image
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm going to stick with your first version because it is shorter. THX!
@Nikolass Shorter code doesn't mean better code. You will have animation issues if you change navigation since you are identifying by index rather than a unique identifier. It's also not particular safe, because these arrays could be an unpredictable size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.