Whenever we find the need to put UIKit and SwiftUI, there are many situations where we’d want to put a UIKit view in a UIKitRepresentable. While we could make an UIKitRepresentable for every kind of View we want to store, in many situations a generic UIKitRepresentable is all we need.

The first style, is to use a type erasure style UIViewRepresentable that does not expose the UIKit view after created. If other code is responsible for managing the UIView, this can be fine.

struct AnyUIViewRepresentable: UIViewRepresentable {
    private let uiView: UIView
    
    init<View: UIView>(uiView: View) {
        self.uiView = uiView
    }
    
    func makeUIView(context: Context) -> UIView {
        uiView
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        // do nothing
    }
}

Then, we could use it like so:

class SomeAdView: UIView {
    // some ad view implementation
}

struct SampleBody: View {
    var body: some View {
        Text("hello")
        AnyUIViewRepresentable(uiView: SomeAdView())
    }
}

However, we could also expose the underlying ui view generically as well if we wanted.

struct AnyUIViewRepresentableExposed<View: UIView>: UIViewRepresentable {
    let uiView: View
    
    init(uiView: View) {
        self.uiView = uiView
    }
    
    func makeUIView(context: Context) -> UIView {
        uiView
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        // do nothing
    }
}

struct SampleBodyExposed: View {
    var body: some View {
        Text("hello")
        AnyUIViewRepresentableExposed(uiView: SomeAdView())
    }
}