I’m trying to build a detail view screen where a user can edit the contents of an object and save it, but I’m struggling to figure out how best to initialize the view.
I’m passing in a “MailFilter” object (which I decoded from a web API) to this view (from a List item’s NavigationLink), and am creating state for each of the fields which need to be editable, such that I can use them with a SwiftUI form. I have a custom initializer to set these parameters (and make sure they aren’t nil—as they can be in the actual filter object).
However, this approach doesn’t seem to work. I’m given errors that I’m trying to use self. before initializing the variables—in the initializer! Is there a different approach I should be taking to get my object’s data into this detail view?
I’m passing in a “MailFilter” object (which I decoded from a web API) to this view (from a List item’s NavigationLink), and am creating state for each of the fields which need to be editable, such that I can use them with a SwiftUI form. I have a custom initializer to set these parameters (and make sure they aren’t nil—as they can be in the actual filter object).
Code Block struct FilterView: View { var filter: MailFilter @State var from: String @State var to: String init(_ filter: MailFilter) { self.filter = filter from = filter.criteria.from ?? "" to = filter.criteria.to ?? "" } var body: some View { Form { Section(header: Text("From")) { TextField("From", text: $from) } Section(header: Text("To")) { TextField("To", text: $to) } } } }
However, this approach doesn’t seem to work. I’m given errors that I’m trying to use self. before initializing the variables—in the initializer! Is there a different approach I should be taking to get my object’s data into this detail view?
hi,
instead of writing
you should be writing
this is a syntactic issue with @State: you need to initialize the property wrapper, not its value.
hope that helps,
DMG
instead of writing
Code Block from = filter.criteria.from ?? "" to = filter.criteria.to ?? ""
you should be writing
Code Block _from = State(initialValue: filter.criteria.from ?? "") _to = State(initialValue: filter.criteria.to ?? "")
this is a syntactic issue with @State: you need to initialize the property wrapper, not its value.
hope that helps,
DMG