When you're just learning SwiftUI, or if you have very simple needs, you'll write navigation code like this:
NavigationStack {
NavigationLink("Tap Me") {
Text("Detail View")
}
}
Sometimes that's absolutely the right thing to do, but it has a hidden problem. To see what it is, I want to create a real detail view that prints a message in its initializer:
struct DetailView: View {
var number: Int
var body: some View {
Text("Detail View \(number)")
}
init(number: Int) {
self.number = number
print("Creating detail view \(number)")
}
}
And now try using that in your navigation code:
NavigationStack {
NavigationLink("Tap Me") {
DetailView(number: 556)
}
}
Go ahead and run the project, but don't tap the navigation link – just run it and look in Xcode's debug console area, because you should see "Creating detail view 556".
What's happening is that just showing the navigation on the screen is enough for SwiftUI to automatically create a detail view instance. Doing that a couple of times is fine, but what if we had something more complex? For example, imagine doing this inside a list of 1000 rows:
NavigationStack {
List(0..<1000) { i in
NavigationLink("Tap Me") {
DetailView(number: i)
}
}
}
Now you'll see lots of DetailView
instances are being created as you scroll around, often more than once. This is making Swift and SwiftUI do a lot more work than is necessary, so when you're dealing with dynamic data – when you have lots of different integers to show in the same way, for example – SwiftUI gives us a better solution: attaching a presentation value to our navigation link.
Let's look at that next…
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.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.