Should a delegate property passed into a struct also be declared as weak in the struct?

The Swift book says that "to prevent strong reference cycles, delegates are declared as weak references."

protocol SomeDelegate: AnyObject {
  
}

class viewController: UIViewController, SomeDelegate {
  weak var delegate: SomeDelegate?
  
  override func viewDidLoad() {
    delegate = self
  }
}

Say the class parameterizes a struct with that delegate

class viewController: UIViewController, SomeDelegate {
  weak var delegate: SomeDelegate?
  
  override func viewDidLoad() {
    delegate = self
    let exampleView = ExampleView(delegate: delegate)
    let hostingController = UIHostingController(rootView: exampleView)
    self.present(hostingController, animated: true)
  }
}

struct ExampleView: View {
  var delegate: SomeDelegate!
  
  var body: some View {
    Text("")
  }
}

Should the delegate property in the struct also be marked with weak?

Should the delegate property in the struct also be marked with weak?

It depends on whether it may create a reference cycle or not.


In the example code you have shown, hostingController may hold a strong reference to ExampleView.delegate, but it is not held as a strong reference in viewController. (Please start type names with Capital letter, even in a simplified example.)

So, you have no need to declare the property ExampleView.delegate as weak.

Generally, in case of View structs, you have no need to care about reference cycles if you are using the View in a usual way.

But, if you are not using the View in a usual way, or the struct is not a View and it may be used in various ways, you may need to place weak on properties which may make reference cycle.

If you do not understand what would be usual nor what might make reference cycles, better use weak even when it is not named delegate.

Should a delegate property passed into a struct also be declared as weak in the struct?
 
 
Q