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?

you can still do that but obviously not doing so can't lead to retain cycles.

note that even when delegate is strong in classes (when it can lead to retain cycles) those retain cycles can be broken by other means (e.g. explicitly/manually broken when needed).

there's at least one "exception to the rule" in Apple API whereas delegate is not weak (URLSession.delegate)

1 Like