Is it OK to use binding to a closure?

Is it OK to use closure, wrapped in a Binding in SwiftUI? Or does it have any downsides? It looks like it's working fine, and I find it useful at times, but I don't see such things in any articles or examples. Are there any reasons to avoid it?

Why would one want to use a binding to a closure? Two real-word examples:

  1. I have a SelectLocationScreen where user search for a location. I need a map region to support the search, but it's located inside a subview MapView which is a wrapper around MKMapView (can't use vanilla MapView due to iOS 15 deploy target). I tried to use a binding to actual MKCoordinateRegion, but turns out MKMapView updates it so frequently it makes my interface unresponsive. Since I need map region only when a user submits the search I settled on binding to a closure.
struct SelectLocationScreen: View {
   @State private var getMapRegionClosure: () -> MKCoordinateRegion = { .default }
   ...
}

struct MapView: UIViewRepresentable {
   @Binding var getMapRegionClosure: () -> MKCoordinateRegion
   ...
}
  1. The same SelectLocationScreen has a search bar and I need to do something if user taps on the submit button. The problem is onSubmit(of: .search) works only where .searchable is defined (i.e. in SelectLocationScreen), but I need to handle the tap in a child view. So again, I use binding to a closure.
struct SelectLocationScreen: View {
   @State private var submitSearchHandler: (String) -> Void = { _ in }
   ...
   var body: some View {
      ...
      .searchable(text: $query, prompt: "...")
      .onSubmit(of: .search) { submitSearchHandler(query) }
   }
}

private struct SearchResultsOverlay: View {
   @Binding var submitSearchHandler: (String) -> Void
   ...
   var body: some View {
   ...
   .onFirstAppear {
         submitSearchHandler = { /* fire MKLocalSearch */ }
      }
   }
}

Anyone?

It is very okay. Using a closure wrapped in a Binding in SwiftUI can be a useful technique in certain scenarios, though there are alternative approaches that are often more straightforward and efficient. However, there are indeed situations where it can be beneficial, as you've shown above.

There are a couple of reasons why you might need to use a binding to a closure which might includes the following.

  1. If you want more granular control over when the value is updated.
  2. Allows you to encapsulate the logic for updating the value within the closure itself.
  3. If you need flexibility in how the value is calculated or updated.
1 Like