Skip to content

Instantly share code, notes, and snippets.

@tovkal
Created June 6, 2024 11:00
Show Gist options
  • Save tovkal/8fb53f6eec846fc4f8804549311deefc to your computer and use it in GitHub Desktop.
Save tovkal/8fb53f6eec846fc4f8804549311deefc to your computer and use it in GitHub Desktop.
How to implement NavigationLink's destination parameter without a closure?
import PlaygroundSupport
import Foundation
import SwiftUI
struct SomeView: View {
var body: some View {
Text("Some")
}
}
struct MyNavigationLink<Destination: View>: View {
let destination: () -> Destination
init(@ViewBuilder destination: @escaping () -> Destination) {
self.destination = destination
}
var body: some View {
NavigationLink(destination: destination) {
Text("Some label")
}
}
}
// What I want
MyNavigationLink(destination: SomeView())
// With a closure it compiles
MyNavigationLink(destination: { SomeView() })
// This is the native component
NavigationLink(destination: SomeView(), label: { Text("Some label") })
@tovkal
Copy link
Author

tovkal commented Jun 6, 2024

struct MyNavigationLink<Destination: View>: View {
    let destination: () -> Destination

    init(
        @ViewBuilder destination: @escaping () -> Destination
    ) {
        self.destination = destination
    }

    init(destination: Destination) {
        self.destination = { destination }
    }

    var body: some View {
        NavigationLink(destination: destination) {
            Text("Some label")
        }
    }
}

Adding the second init fixes the problem. This init is not in Apple's docs, but you can see it if you go into NavigationLink's code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment