skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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: {})
      }
    }
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search