Dan
Dan

Reputation: 663

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?

Upvotes: 2

Views: 1103

Answers (1)

Ashley Mills
Ashley Mills

Reputation: 53111

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()
    }
}

Upvotes: 7

Related Questions