---- Updated to provide a reproducible example ----
Following is my View file. I'd like to have each navigation link destination linked to a view model stored in a dictionary (represented by a simple string in the example).
However, the following piece of code doesn't work and each item always displays nothing, even though I tried the solution in SwiftUI NavigationLink loads destination view immediately, without clicking
struct ContentView: View {
private var indices: [Int] = [1, 2, 3, 4]
@State var strings: [Int: String] = [:]
var body: some View {
NavigationView {
List {
ForEach(indices, id: \.self) { index in
NavigationLink {
NavigationLazyView(view(for: index))
} label: {
Text("\(index)")
}
}
}
.onAppear {
indices.forEach { index in
strings[index] = "Index: \(index)"
}
print(strings.keys)
}
}
}
@ViewBuilder
func view(for index: Int) -> some View {
if let str = strings[index] {
Text(str)
}
}
}
struct NavigationLazyView<Content: View>: View {
let build: () -> Content
init(_ build: @autoclosure @escaping () -> Content) {
self.build = build
}
var body: Content {
build()
}
}