Home > Mobile >  How to avoid initializing a struct when using NavigationLink
How to avoid initializing a struct when using NavigationLink

Time:06-01

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
}

CodePudding user response:

Rather than hardcoding destination in the parent view you can inject a ViewBuilder that will be passed to NavigationLink, something like:

struct ProfileConfiguration<CardView: View>: View {

  let cardViewBuilder: () -> CardView

  init(@ViewBuilder cardViewBuilder: @escaping () -> CardView) {
    self.cardViewBuilder = cardViewBuilder
  }

  var body: some View {
    NavigationLink(destination: cardViewBuilder, label: {})
  }
}

CodePudding user response:

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

CodePudding user response:

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.

struct ConfigurationCardView: View {
var person: Person = Person.init(name: "",bio: "",location: "")
var body: some View {
    //Content
}

}

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.

  • Related