【发布时间】:2014-06-03 20:35:24
【问题描述】:
为了实现委托,我需要使类符合 Swift 中的协议。我该怎么做?
【问题讨论】:
为了实现委托,我需要使类符合 Swift 中的协议。我该怎么做?
【问题讨论】:
class YourClass: SuperClassIfAny, FirstProtocol, SecondProtocol {
}
但请注意,某些协议要求您实现委托方法。例如,UITableViewDataSource要求您实施
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
和
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
如果那些不是由符合协议的类实现的,Xcode 会给你一个编译错误(总是检查协议声明,Cmd + Click 会告诉你你必须实现哪些方法)。
【讨论】:
Xcode 6 beta 7 略微更改了 UITableViewDataSource 的协议,以在两个必需的实现上匹配以下语法:
6b7 : UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!
与 6b6 相比
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell
主要区别在于 UITableView、NSIndexPath 和 UITableViewCell 不再是 'Implicitly Unwrapped Optionals'
【讨论】: