TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

The problem with a simple NavigationLink

Paul Hudson    @twostraws   

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…

Hacking with Swift is sponsored by RevenueCat.

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.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.