如何创建具有弱类的,符合通用协议的基类? [英] How do you create a base class with a weak delegate that conforms to a generic protocol?

查看:88
本文介绍了如何创建具有弱类的,符合通用协议的基类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为UIView创建一个基类,该基类要求委托符合View定义的特定协议。

I want to create a base class for UIViews that require that a delegate conform to a specific protocol defined by the View.

class BaseView<P>: UIView {
    weak var delegate: P?
}

protocol MyProtocol {}

class MyView: BaseView<MyProtocol> {}

这给了我一个错误:'weak'一定不能应用于非class-绑定 T;请考虑添加具有类绑定的协议一致性。

This gives me the error: "'weak' must not be applied to non-class-bound 'T'; consider adding a protocol conformance that has a class bound".

如何解决此错误?还是周围有工作?还是不必首先使委托变量变弱?

How do I fix this error? Or is there some work around? Or is it not so necessary to make the delegate variable weak in the first place? Thanks in advance.

推荐答案

由于弱是分配给类类型而不是结构的任何东西的属性,因此您必须显式将您的通用参数限制为类类型,您可以通过以下方式进行操作:

Since weak is a property assigned to anything that is of class type and not struct, you have to explicitly constraint your generic parameter to be of class type and you do that this way:

class BaseView<P: AnyObject>: UIView {
    weak var delegate: P?
}

@objc protocol MyProtocol {

}

class MyView: BaseView<MyProtocol> {

}

只需要澄清一下。通常,通常使协议成为类类型,您可以通过以下方式使其符合类:

Only one need of clarification. Usually to make a protocol be of class type usally you would make it conform to class this way:

protocol MyProtocol: class { }

但是,由于某种原因,如果您这样做,编译器会抛出错误。我了解到,这是一个可以在此处了解更多信息的错误:

However, for some reason the compiler throws an error if you were to do it that way. I learned that this is a bug that could be learned about more here:

如何要求一个协议只能被一个特定的类所采用

因此添加 @objc 有助于使警告和错误均消失。

So adding the @objc helps silence the warning and error both.

这篇关于如何创建具有弱类的,符合通用协议的基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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