如何使一个类符合Swift协议?
在Objective-C中:
@interface CustomDataSource : NSObject <UITableViewDataSource> @end 在Swift中:
 class CustomDataSource : UITableViewDataSource { } 
但是,将出现错误消息:
- types“CellDatasDataSource”不符合协议“NSObjectProtocol”
- types“CellDatasDataSource”不符合协议“UITableViewDataSource”
什么应该是正确的方法?
types“CellDatasDataSource”不符合协议“NSObjectProtocol”
 你必须让你的类从NSObjectinheritance来符合NSObjectProtocol 。 香草Swift类没有。 但UIKit很多部分都期望NSObject 。 
 class CustomDataSource : NSObject, UITableViewDataSource { } 
但是这个:
types“CellDatasDataSource”不符合协议“UITableViewDataSource”
是期待。 直到你的类实现了协议的所有必需的方法,你将会得到错误。
所以得到编码:)
在遵守协议之前,类必须从父类inheritance。 主要有两种方法。
 一种方法是让你的类inheritance自NSObject并一起符合UITableViewDataSource 。 现在如果你想修改协议中的函数,你需要在函数调用之前添加关键字override ,就像这样 
 class CustomDataSource : NSObject, UITableViewDataSource { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } } 
 然而,这有时会让你的代码混乱,因为你可能有许多协议要遵守,每个协议可能有几个代理function。 在这种情况下,可以使用extension名将协议符合代码从主类中分离出来,而不需要在扩展名中添加override关键字。 所以相当于上面的代码将是 
 class CustomDataSource : NSObject{ // Configure the object... } extension CustomDataSource: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } } 
Xcode 9有助于实现Swift数据源和代表的所有强制方法。
 这里是UITableViewDataSource例子: 
显示警告/提示以实施强制性方法:
  
 
点击“修复”button,它会在代码中添加所有必需的方法:
 