为任何实现多个协议的对象定义一个 Swift 类型别名
Define a Swift typealias for any object that implements multiple protocols
我正在尝试为符合多个协议的 UITableViewCell 委托 属性 定义 typealias
。这就是我想要做的,Swift 抱怨我的语法错误:
// The typealias definition
typealias CellDelegate = AnyObject<UIPickerViewDataSource, UIPickerViewDelegate>
// In my UITableViewCell subclass:
weak var delegate: CellDelegate?
"Cannot specialize the non-generic type AnyObject" 是我遇到的错误。我该如何正确执行此操作?
我不明白你为什么要这样输入weak var delegate: <CellDelegate>?
为什么你不这样输入weak var delegate: CellDelegate?
问题是 AnyObject 是通用的。在第一行中,您尝试使 AnyObject 成为非泛型,但事实并非如此。
你最好制作一个 class 来实现这些(数据源和委托)。
你应该传递一个已知的对象,AnyObject 太通用了,这就是你不能这样做的原因
如果你想声明多协议:
protocol<A, B>
您发布的代码与您预期的含义不同。您将 AnyObject
视为通用类型,将 UIPickerViewDataSource
和 UIPickerViewDelegate
作为类型参数。这与使用 Int
键和 String
值创建 Dictionary
相同,例如:
var someDictionary: Dictionary<Int, String>
您要完成的任务需要一个不同的构造,称为 协议组合 。 Swift 专门提供它来表达符合多种协议的类型。它的语法如下,你可以在任何可以使用常规类型的地方使用它:
FirstProtocol & SecondProtocol
使用此功能,您的代码将变为:
// The typealias definition
typealias CellDelegate = UIPickerViewDataSource & UIPickerViewDelegate
// In my UITableViewCell subclass:
weak var delegate: CellDelegate?
Apple 的 Swift 语言指南中解释了协议组成,here。
编辑: 更新为 Swift 3 语法,感谢@raginmari
使用 Swift 3,语法发生了变化。
直到 Swift 2.3:
typealias CellDelegate = protocol<UIPickerViewDataSource, UIPickerViewDelegate>
自 Swift 3:
typealias CellDelegate = UIPickerViewDataSource & UIPickerViewDelegate
我正在尝试为符合多个协议的 UITableViewCell 委托 属性 定义 typealias
。这就是我想要做的,Swift 抱怨我的语法错误:
// The typealias definition
typealias CellDelegate = AnyObject<UIPickerViewDataSource, UIPickerViewDelegate>
// In my UITableViewCell subclass:
weak var delegate: CellDelegate?
"Cannot specialize the non-generic type AnyObject" 是我遇到的错误。我该如何正确执行此操作?
我不明白你为什么要这样输入weak var delegate: <CellDelegate>?
为什么你不这样输入weak var delegate: CellDelegate?
问题是 AnyObject 是通用的。在第一行中,您尝试使 AnyObject 成为非泛型,但事实并非如此。
你最好制作一个 class 来实现这些(数据源和委托)。
你应该传递一个已知的对象,AnyObject 太通用了,这就是你不能这样做的原因
如果你想声明多协议:
protocol<A, B>
您发布的代码与您预期的含义不同。您将 AnyObject
视为通用类型,将 UIPickerViewDataSource
和 UIPickerViewDelegate
作为类型参数。这与使用 Int
键和 String
值创建 Dictionary
相同,例如:
var someDictionary: Dictionary<Int, String>
您要完成的任务需要一个不同的构造,称为 协议组合 。 Swift 专门提供它来表达符合多种协议的类型。它的语法如下,你可以在任何可以使用常规类型的地方使用它:
FirstProtocol & SecondProtocol
使用此功能,您的代码将变为:
// The typealias definition
typealias CellDelegate = UIPickerViewDataSource & UIPickerViewDelegate
// In my UITableViewCell subclass:
weak var delegate: CellDelegate?
Apple 的 Swift 语言指南中解释了协议组成,here。
编辑: 更新为 Swift 3 语法,感谢@raginmari
使用 Swift 3,语法发生了变化。
直到 Swift 2.3:
typealias CellDelegate = protocol<UIPickerViewDataSource, UIPickerViewDelegate>
自 Swift 3:
typealias CellDelegate = UIPickerViewDataSource & UIPickerViewDelegate