Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass callback to View init

This example works, but if I need to add an init to do some prep work, I can’t figure out hot to pass the callback. In the actual code I need to pass several parameters and do some other initialization.

import SwiftUI

struct Choices: View
{
    let choices = ["One", "Two", "Three"]
    @State var choice:String = "One"
    let callback: (String) -> ()
    
/*
init()
{
  // do stuff here
}
*/

    var body: some View
    {
        VStack(alignment: .leading)
        {
            ForEach(choices, id:\.self)
            { c in
                HStack
                {
                    Image(systemName: (choice == c) ? "checkmark.square" : "square")
                    Text(c)
                }.onTapGesture
                {
                    choice = c
                    callback(c)
                }
            }
            Divider()
        }.padding()
    }
}

struct ChoicesContentView: View
{
    @State var answers:[String] = ["","",""]
    
    var body: some View
    {
        VStack(alignment: .leading)
        {
            ForEach(0..<3)
            { i in
                Choices()
                {
                    ans in
                    print(ans)
                }
                Text("Selected: \(answers[i])")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ChoicesContentView()
    }
}

How to I pass the callback as a parameter?

Thanks for the help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It can be like

struct Choices: View
{
    let choices = ["One", "Two", "Three"]
    @State var choice:String = "One"
    let callback: (String) -> ()
    
    init(callback: @escaping (String) -> ()) {    // << here !!
        self.callback = callback
    }
// ...
}

or even with default value

init(callback: @escaping (String) -> () = { _ in }) {    // << here !!
    self.callback = callback
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading