How to put a function that returns void in SwiftUI Preview's parameters

Viewed 1293

I'm trying to use this function:

var handler: (String, (Bool) -> Void) -> Void

And the error displayed in the preview provider is that there's a missing argument for the parameter in call, but I don't know how to do that properly.

Insert ', handler: <#(String, (Bool) -> Void) -> Void#>'

If you have some documentation or explanation about handling these types of data in the preview provider I'd be really grateful.

3 Answers

This is a little tricky because of the closure-within-a-closure. Xcode doesn't seem to want to inline the second closure, but assuming it's defined outside of it, it seems to work fine:

struct MyView : View {
    var handler: (String, (Bool) -> Void) -> Void
    
    var body: some View {
        Text("Hello, world")
    }
}

struct TestView_Preview : PreviewProvider {
    static var boolHander : (Bool) -> Void = { _ in }
    
    static var previews: some View {
        MyView(handler:{ myString, boolHander in })
    }
}

I'm making some assumptions here, since you didn't actually include any code showing where/how it was defined, but hopefully this gets you moving in the right direction.

It seems that the problem was that there was no initial value for "handler", which is taken somehow as a Binding, so the preview provider and the parent view asked for the value.

Putting = { _ , _ in } as the initial value for "handler" solved the problem.

struct MyView: View {
    var handler: () -> ()

    var body: some View {
    Text("Hello, world")
   }
}

struct MyView_Preview: PreviewProvider {    
  static var previews: some View {
     MyView(handler: {})
   }
}

and this for two closures: 

struct MyView: View {
var handler: (() -> ()) -> ()

var body: some View {
    Text("Hello, World!")
 }
}

struct MyView_Previews: PreviewProvider {
static var previews: some View {
    MyView(handler: { _ in } )
  }
}
Related