UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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…

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.