BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

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…

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.