如何使用符合通用协议的弱委托创建基础 class?

How do you create a base class with a weak delegate that conforms to a generic protocol?

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

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

protocol MyProtocol {}

class MyView: BaseView<MyProtocol> {}

这给了我错误:“'weak' 不得应用于非 class-绑定 'T';考虑添加具有 class 的协议一致性边界”。

如何修复此错误?或者有一些解决方法吗?还是一开始就没有必要让委托变量变弱?提前致谢。

您应该通过添加 MyProtocol 为您的泛型添加类型约束,并创建一个符合 MyProtocol.

的 class

您可以找到更多信息 here

更新代码:

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

protocol MyProtocol: class {}

class MyProtocolImp: MyProtocol {

}

class MyView: BaseView<MyProtocolImp> {

}

但是我不知道你为什么在class中使用P参数。 你可以不用这个写:

class BaseView: UIView {
    weak var delegate: MyProtocol?
}

protocol MyProtocol: class {}

class MyView: BaseView {

}

因为 weak 是一个 属性 分配给 class 类型而不是结构的任何东西,你必须明确地将你的泛型参数限制为 class 类型并且你这样做这样:

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

@objc protocol MyProtocol {

}

class MyView: BaseView<MyProtocol> {

}

只有一个需要说明。通常要使协议成为 class 类型,通常您会以这种方式使其符合 class:

protocol MyProtocol: class { }

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

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