Swift中的纯类协议 [英] Class-Only Protocols in Swift

查看:162
本文介绍了Swift中的纯类协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的一些课程(不是全部)能够使用'Class-Only Protocols'。我正在做的是

I want some of my classes (not all) to conform using 'Class-Only Protocols' from docs. What I am doing is

protocol RefreshData: class, ClassA, ClassB
{
    func updateController()
}

我收到错误

non class type 'RefreshData cannot inherit from classA
non class type 'RefreshData cannot inherit from classB

我不确定我是否完全按照文档进行操作。有没有人对此有任何想法?

I'm not sure I am following exactly as in the docs. Does anyone have any ideas about this?

推荐答案

Swift 4允许您组合类型,因此您可以拥有自己的协议,然后创建一个类型别名将它与特定的班级要求结合起来。

Swift 4 allows you to combine types, so you can have your protocol and then create, for example, a type alias to combine it with a specific class requirement.

对于(一个人为的)例子:

For (a contrived) example:

typealias PresentableVC = UIViewController & Presentable






对于提供的代码:


For the presented code:

问题是你试图限制特定的类,Swift不能这样做(目前无论如何)。您只能限制类并继承其他协议。您的语法是用于协议继承,但您尝试将其用作类限制。

The problem is that you're trying to limit to specific classes and Swift can't do that (at the moment anyway). You can only limit to classes and inherit from other protocols. Your syntax is for protocol inheritance but you're trying to use it as a class limitation.

请注意,类协议的目的是:

Note that the purpose of class protocols is:


当该协议的要求定义的行为假定或要求符合类型具有引用语义而不是值语义时,使用仅类协议。

Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics.

这篇关于Swift中的纯类协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆