为任何实现多个协议的对象定义Swift类型

Mat*_*ros 25 cocoa-touch ios swift

我正在尝试为typealias符合多个协议的UITableViewCell的委托属性定义一个.这就是我想要做的,Swift抱怨我的语法错误:

// The typealias definition
typealias CellDelegate = AnyObject<UIPickerViewDataSource, UIPickerViewDelegate>

// In my UITableViewCell subclass:
weak var delegate: CellDelegate?
Run Code Online (Sandbox Code Playgroud)

"不能专门化非泛型类型AnyObject"是我得到的错误.我该怎么做呢?

Eli*_*eda 29

您发布的代码与您期望的含义不同.您将AnyObject其视为泛型类型,使用UIPickerViewDataSourceUIPickerViewDelegate作为类型参数.这与创建Dictionarywith Int键和String值是一回事,例如:

var someDictionary: Dictionary<Int, String>
Run Code Online (Sandbox Code Playgroud)

您要完成的任务需要一个不同的结构,称为协议组合.Swift专门提供它来表达符合多种协议的类型.它的语法如下,您可以在任何可以使用常规类型的地方使用它:

FirstProtocol & SecondProtocol
Run Code Online (Sandbox Code Playgroud)

使用此功能,您的代码将变为:

// The typealias definition
typealias CellDelegate = UIPickerViewDataSource & UIPickerViewDelegate

// In my UITableViewCell subclass:
weak var delegate: CellDelegate?
Run Code Online (Sandbox Code Playgroud)

协议组成采用的是苹果指南解释了雨燕的语言,在这里.

编辑:更新为Swift 3语法,谢谢@raginmari

  • 在Swift 3中,语法已更改为`typealias CellDelegate = UIPickerViewDataSource&UIPickerViewDelegate`. (3认同)