Avatar ·

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

Hi everyone! I'm new to Swift and ran into a problem implementing the delegate pattern. I have a protocol `MyDelegate` and a class `ViewController` that should be the delegate for another class `Service`. I want the `delegate` property in `Service` to be a weak reference to avoid strong reference cycles and memory leaks. Here's my code: ```swift protocol MyDelegate { func didSomething() } class Service { weak var delegate: MyDelegate? // Error: 'weak' cannot be applied to non-class type 'MyDelegate' func performTask() { delegate?.didSomething() } } class ViewController: MyDelegate { func didSomething() { print("Work done!") } } ``` Xcode gives an error: `'weak' cannot be applied to non-class typ`