Class Only Protocols In Swift 5

几行简单的代码

protocol KLineViewDataSource {
}
class KLineView: UIView {
    weak var dataSource: DataSource?
}

定义一个协议KLineViewDataSource,然后在KLineView类里使用,防止循环引用,加上weak。但是会报错

1792315-d893c75717a6c696.png
compile error.png

'weak' must not be applied to non-class-bound 'KLineViewDataSource'; consider adding a protocol conformance that has a class bound
大意就是,weak不能修饰非类的类型

Swift里,你定义一个这样的协议

protocol KLineViewDataSource {
}

类和结构体都可以来遵守,所以,到时候,作为属性的var dataSource: KLineViewDataSource?可能会接受一个遵守协议的结构体,但是,weak只能修饰类,所以就会有矛盾。要么不用weak,要么限制这个协议只能是类来遵守。

这里用后者,也就是标题Class Only Protocols。

Swift提供了提供了两种方式,一种是

protocol KLineViewDataSource: AnyObject { 
}
protocol KLineViewDataSource: class {
}

区别就是,继承的类不一样,一个是继承AnyObject,一个是继承class。这两种方式,效果一样,没有区别。只是在Swift 5class已经没有了。

参考:
What's the difference between a protocol extended from AnyObject and a class-only protocol?

Class Only Protocols In Swift 4

Class-only protocols, class vs AnyObject?

猜你喜欢

转载自blog.csdn.net/weixin_34247155/article/details/90993429