Avatar ·

如何在纯 Swift 中创建对协议的弱引用(不使用 @objc)

大家好!我是 Swift 新手,在实现委托模式时遇到了一个问题。 我有一个协议 `MyDelegate` 和一个类 `ViewController`,它应该是另一个类 `Service` 的委托。我希望 `Service` 中的 `delegate` 属性是弱引用(weak),以避免强引用循环和内存泄漏。 这是我的代码: ```swift protocol MyDelegate { func didSomething() } class Service { weak var delegate: MyDelegate? // 错误:'weak' cannot be applied to non-class type 'MyDelegate' func performTask() { delegate?.didSomething() } } class ViewController: MyDelegate { func didSomething() { print("工作完成!") } } ``` Xcode 报错:`'weak' cannot be applied to non-class type 'MyDelegate'`。我知道 `weak` 只适用于引用类型(类),但协议可以被类和结构体遵循。 如何正确创建对协议的弱引用?