【发布时间】:2020-11-06 22:51:19
【问题描述】:
我可以部分用 Objective C 部分用 Swift 实现一个协议吗?
我有一个现有的 Objective C 类,它在 .h 文件中这样声明。
@interface SetupViewController : UIViewController <UITableViewDataSource> {
// etc.
}
对应的 .m 文件实现了 UITableViewDataSource 协议。现在我想在 Swift 扩展中重写其中的一些方法。但我希望现在不必用 Swift 重写所有这些。 (这只是一个示例 sn-p,实际的类要长得多。)
@implementation SetupViewController
// I want to rewrite this method in Swift
/*
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
*/
// I don't want to rewrite this method in Swift yet
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// lots of code
}
所以我将其中一种方法从 Objective C 文件中移到了我的扩展中,如下所示:
@objc extension SetupViewController {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// new, more involved code
}
}
但这不会编译。我收到一条错误消息Method 'tableView(_:numberOfRowsInSection:)' with Objective-C selector 'tableView:numberOfRowsInSection:' conflicts with previous declaration with the same Objective-C selector。但是我的Objective-C文件里已经没有numberOfRowsInSection方法了,我把它拿出来了。
似乎只是将 UITableViewDataSource 放在 .h 文件中会使 Swift 扩展认为已经实现了实现协议的方法。
我也尝试将扩展名声明为 @objc extension SetupViewController: UITableViewDataSource 并将其从 .h 文件中删除,但由于扩展名本身没有实现协议,所以失败了。
【问题讨论】:
标签: ios objective-c swift