Class Protocol in a SwiftUI struct View

I'm attempting to use a UIView subclass in a SwiftUI View-Based design


class MyView: UIView {
   weak var delegate: MyViewDelegate?
...
}

protocol MyViewDelegate: class {
   func somethingHappened()
}


I was hoping I could just do something like:


struct WrapperView: UIViewRepresentable {
   func makeUIView(context: Context) -> MyView {
       let result = MyView()
       result.delegate = self
       return result
   }
}

extension WrapperView: MyViewDelegate {
   func somethingHappened() {
       // do delegate stuff
   }
}


I find myself in a catch-22

WrapperView can not implement MyViewDelegate because it's a class protocol.

If I change the protocol to not be class-based, the delegate iVar can no longer be weak.

If I remove the weak reference from the delegate var, (I believe) I will be creating a retain cycle any time MyView's delegate ivar is class.


I certainly get why weak (and reference counting) are class only, but is there some way I can define the delegate protocol to allow the delegate ivar to be weak, but still possibly refer to struct?

my plan B is to change WrapperView to something like:


struct WrapperView: UIViewRepresentable {
   var wrappedViewDelegate: WrappedViewDelegate {
       return WrappedViewDelegate(parent: self)   
   }
   func makeUIView(context: Context) -> MyView {
       let result = MyView()
       result.delegate = wrappedViewDelegate
       return result
   }
   func somethingHappened() {
       // do delegate stuff
   }
}
class WrappedViewDelegate: MyViewDelegate {
   weak var parent: WrapperView

   init(parent: WrapperView) {
       parent = parent
   }

   func somethingHappened() {
       parent.somethingHappened()
   }
}

Does anyone see an alternative to my planB?

thanks!

Class Protocol in a SwiftUI struct View
 
 
Q