Home > front end >  Passing data from child to parent, with an init in the child
Passing data from child to parent, with an init in the child

Time:12-14

I am trying to pass data from my child view to the parent view. I also pass some data from the parent to the child.

struct Parent: View {
...
    var body: some View {
        OneColumnList(changeStage: changeStage, icons: icons, options: options)
        ...
struct Child: View {
    var changeStage: (Int) -> ()
    var icons: [String]
    var options: [String]
    
    init(icons: [String], options: [String]) {
        self.icons = icons
        self.options = options
    }
...

I currently get this error on the child:

Return from initializer without initializing all stored properties

I guess I need to initialise changeStage, but I can't work out how to do it. I'd appreciate any help!

CodePudding user response:

I think you need to enhance your init method of the Child. E.g.

 init(changeState: @escaping (Int) -> (), icons: [String], options: [String]) {
        self.changeState = changeState
        self.icons = icons
        self.options = options
    }

Then you can handle the state changes in your Parent, like for example

Child(changeState: { myInt in print(myInt) }, icons: icons, options: options)

CodePudding user response:

changeState according to its type should be a completion block, that receives one Int argument and returns Void. Try adding this to the init:

self.changeState = { someNumber in }
  • Related