Every time I use NavigationLink the destination parameter needs the struct’s objects to be initialized, making unnecessary and messy code.
//View which will send me to another view using NavigationLink()
struct ProfileConfiguration: View {
NavigationLink(destination: ConfigurationCardView(person: Person.init(name: "",
bio: "",
location: ""))
)
}
//The destination view, which has the struct Person:
struct ConfigurationCardView: View {
var person: Person
var body: some View {
//Content
}
}
//The struct Person, with some variables:
struct Person: Hashable, Identifiable {
var name: String
var personImages: [UIImage?] = []
var bio: String
var location: String
}
3
Answers
It is not unnecessary, some views need those parameters to display the relevant data.
However, if you want you could make that parameter optional or provide a default value so you wouldn’t have to pass it one
Rather than hardcoding destination in the parent view you can inject a
ViewBuilder
that will be passed toNavigationLink
, something like:There are 2 approaches you can achieve this.
1 tell swift that object can hold nil value defining by ?
(var person: Person?)
2 assign some value to person object in ConfigurationCardView, so swift will not ask to pass person object.
}
in 1 approach, it will still allow (not mandatory) you to pass person object from outside where you are creating NavigationLink.
in 2 approach, if you define person with var, it will still allow (not mandatory) you to pass person object from outside where you are creating NavigationLink.
But if you define with let, it will not allow you to pass person object from outside.