Avatar ·

How to make a weak reference to a protocol in pure Swift (without @objc)

Hi everyone! I'm learning Swift and trying to implement the delegate pattern, but I've run into a memory leak issue. I have a protocol: ```swift protocol MyDelegate: class { func didSomething() } class MyClass { var delegate: MyDelegate? func doSomething() { delegate?.didSomething() } } ``` I know that in Objective-C you could use `weak` for protocols marked with `@objc`. But I want to write in pure Swift. When I try to do: ```swift weak var delegate: MyDelegate? ``` The compiler gives an error: `'weak' may only be applied to class and class-bound protocol types`. I've read that I need to inherit the protocol from `AnyObject` or use `class` in the protocol definition. But I don't fully understand how this works and what the difference is.