Class-only Protocols - class or AnyObject

iOS 系统中广泛使用了 delegate 模式,如果有 Swift 开发经验的话,你将会发现如下代码无法正常通过编译。
报错信息如下:
'weak' must not be applied to non-class-bound 'MyDelegate'; consider adding a protocol conformance that has a class bound
因为使用了 weak 关键字,必须让该 protocol 满足 class 类型。
如果像上面这样声明一个 class-only 的 protocol 的话,你可能很早就开始接触 Swift 了。你可能还没意识到 : class 语法将不再是推荐的声明方式。
虽然编译器目前没有输出任何警告信息,但是从 Swift 4 开始,该关键字已被废弃了。
This proposal merges the concepts of class and AnyObject, which now have the same meaning: they represent an existential for classes. To get rid of the duplication, we suggest only keeping AnyObject around. To reduce source-breakage to a minimum, class could be redefined as typealias class = AnyObject and give a deprecation warning on class for the first version of Swift this proposal is implemented in. Later, class could be removed in a subsequent version of Swift.
你应该使用 AnyObject 来替代。
应该如何处理
对于需要 class-only 的 protocol,从现在开始全部使用 AnyObject 关键字来替代 class 。
总结
虽然使用 class 关键字编译器现在并不会报错,但是为了保险起见,应该统一使用 AnyObject。因为 class 可能在未来会被移除掉。而且,class 关键字也不再出现于官方 Swift documentation 中,对于一个新手而言,他可能并不知道 class 这个关键字。
版权声明: 本文为 InfoQ 作者【SwiftMic】的原创文章。
原文链接:【http://xie.infoq.cn/article/daf263535304bfd8c3b141da0】。文章转载请联系作者。
评论