Search code examples
swiftuiswiftui-navigationlinkios16swiftui-navigationstack

SwiftUI NavigationStack NavigationLink same Value, multiple destinations


I have a model like so...

struct User: Codable {
    let followersCount: Int
    let followingCount: Int
}

Using NavigationStack I would like to be able to use NavigationLink based on Value

 NavigationLink(value: user.followersCount) {
    Text("Followers")
}

NavigationLink(value: user.followingCount) {
    Text("Following")
}
.navigationDestination(for: Int.self) { _ in
    FollowersView()
}

.navigationDestination(for: Int.self) { _ in
    FollowingView()
}

As both values are an Int. Is there a way to differentiate the two?


Solution

  • Declare an object:

    enum Link {
       case followers(Int)
       case following(Int)
    }
    

    then use it like:

    NavigationLink(value: Link.followers(user.followersCount)) {
        Text("Followers")
    }
    
    NavigationLink(value: Link.following(user.followingCount)) {
        Text("Following")
    }
    
    .navigationDestination(for: Link) { link in
        switch link {
        case let .followers(count):
            FollowersView()
        case let .following(count):
            FollowingView()
        }
    }