Home > Enterprise >  How to pass callback to View init
How to pass callback to View init

Time:07-15

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.

CodePudding user response:

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
}
  • Related