Search code examples
swiftswiftui

What the difference between wrapping a NavigationLink with a ForEach and using .navigationDestination


I was following a SWIFTUI tutorial and for one of the challenges me and the instructor created the same functionality but out code differed

his approach:

var body: some View {
    NavigationStack {
        List(users) { user in
            NavigationLink(value: user) {
            HStack {
                Circle()
                    .fill(user.isActive ? .green : .red)
                    .frame(width: 30)
                
                Text(user.name)
            }
        }
    }
    .navigationTitle("Friendface")
    .navigationDestination(for: User.self) { user in
        DetailView(user:user)
    }
    .task {
        await loadData()
    }

and my approach:

    NavigationStack{
        List {
            ForEach(users) { user in
                
                NavigationLink{
                    DetailView(user:user)
                label: {
                    HStack {
                        Circle()
                            .fill(user.isActive ? .green : .red)
                            .frame(width: 30)
                        
                        Text(user.name)
                    }
                }
                    
                }
                
            }
            
        }
        .task {
            await loadData()
        }
    }

whats the difference between the two approaches in terms of readability and scalability?


Solution

  • The difference is that when you don't use .navigationDestination whatever is inside the navigationLink will get created as soon as the app starts, which is fine when you aren't iterating through a large list but if your navigationLink is in a large List you have to use .navigationDestination if you do not want the views to be created automatically