Given the following code:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
ForEach(0..<3) { index in
NavigationLink(destination: TestView(index)) {
Text("Hello, world!")
}
}
}
}
}
}
struct TestView: View {
let id = UUID()
init(_ index: Int) {
print("\(id) \(index)")
}
var body: some View {
Text("Hello world!")
}
}
I would expect three lines to be printed to the console, but there are six, two for each index. Every id of the TestView is different.
Is this expected behavior?
UPDATE: Using NavigationStack, every index gets printed four times!
EDIT:
struct ContentView: View {
static var indices = Set<Int>()
var body: some View {
NavigationView {
VStack {
ForEach(0..<3) { index in
NavigationLink(destination: generateTestView(index) as? TestView) {
Text("Hello, world!")
}
}
}
}
}
func generateTestView(_ index: Int) -> any View {
if !Self.indices.contains(index) {
Self.indices.insert(index)
return EmptyView()
}
return TestView(index)
}
}
The links lead to the TestView instead of the EmptyView, indicating that the View created last is the one we actually use.