在Swift中委托不同类型的属性

Sta*_*ida 7 swift

好的,我们有UIScrollView声明:

protocol UIScrollViewDelegate: NSObjectProtocol { ... }
class UIScrollView: UIView {
    ...
    weak var delegate: UIScrollViewDelegate?
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后UITableViewdelegate变种?

protocol UITableViewDelegate: NSObjectProtocol, UIScrollViewDelegate { ... }
class UITableView: UIScrollView {
    ...
    weak var delegate: UITableViewDelegate?
    ...
}
Run Code Online (Sandbox Code Playgroud)

Apple如何做到这一点?当我做我的

protocol MyScrollViewSubclassDelegate: NSObjectProtocol, UIScrollViewDelegate { ... }
class MyScrollViewSubclass: UIScrollView {
    ...
    weak var delegate: MyScrollViewSubclassDelegate?
    ...
}
Run Code Online (Sandbox Code Playgroud)

使用'MyScrollViewSubclassDelegate'类型获取Property'委托' 不能覆盖类型为'UIScrollViewDelegate?'的属性 .

小智 2

MyScrollViewSubclass 具有 UIScrollView 的 delegate 属性,因为它是 UIScrollView 的子类。

正如delegateUIScrollView 已经定义的那样,您不能使用新类型定义相同的属性名称。

将变量名称更改delegatemyDelegate(或其他名称),它应该可以工作。