Class-only Protocols – class or AnyObject

iOS 系统中广泛使用了 delegate 模式,如果有 Swift 开发经验的话,你将会发现如下代码无法正常通过编译。

class MyClass {
  weak var delegate: MyDelegate?
}

protocol MyDelegate {
}

报错信息如下:

‘weak’ must not be applied to non-class-bound ‘MyDelegate’; consider adding a protocol conformance that has a class bound

因为使用了 weak 关键字,必须让该 protocol 满足 class 类型。

protocol MyDelegate: class {

}

继续阅读“Class-only Protocols – class or AnyObject”