#Preview with a Closure Having Multiple Values to Retrun

I have a simple SwiftUI View like the following.

struct TestView: View {
    var callBack: ((String) -> Void)
    
    var body: some View {
        Button {
            callBack("George")
        } label: {
            Text("Done!")
                .frame(width: 72)
        }
    }
}

#Preview("Test") {
    let callBack: (String) -> Void = { _ in }
    TestView(callBack: callBack)
}

So I'm returning a String variable with a closure. If I have two variables to return with a closure, I only make the callBack guy optional in order to avoid having an error (Constant 'callBack' used before being initialized) in preview.

struct TestView: View {
    var callBack: ((String, Int) -> Void)?
    
    var body: some View {
        Button {
            callBack?("George", 48)
        } label: {
            Text("Done!")
                .frame(width: 72)
        }
    }
}

#Preview("TestView") {
    TestView()
}

I wonder if I can return more than one variable without having an error in Preview? Thanks a lot.

  1. What you have is not called "returning multiple values". Instead, your closure has "multiple parameters".

This is what returning multiple values looks like:

() -> (String, Int)
  1. A piece of code is not a guy—it is not even gender-neutral because it is not anthropomorphic.

  2. This is how you spell a closure that takes two parameters but disregards them and does nothing:

struct TestView: View {
  var callBack: (String, Int) -> Void
  var body: some View { EmptyView() }
}

#Preview("TestView") {
  TestView { _, _ in }
}
2 Likes

Thanks a lot.

1 Like