【发布时间】:2017-09-15 23:06:54
【问题描述】:
我遇到了一个奇怪的问题,一个项目无法在相对较大的混合 ObjC/Swift 项目中实现 swift 协议。
我们的工作项目是关于应用程序 50K 行代码,以及大约 20 个 Cocoapods。该项目最初是一个 ObjC 项目,但现在大约 60% 的 Swift3 和 40% 的 ObjC。
我正在开发 Xcode 8.3.3,但在 XCode 9-GM 中也看到了问题
cocoapods 是 Swift 和 ObjC 的混合体。这一切都很好,所以通常从 ObjC 调用 swift 或从 Swift 调用 ObjC 都可以正常工作。
不过,这可能是我第一次尝试在 UIViewController 中实现 Swift 协议(标有 @objc 标志)。
我最近添加了 cocoapod CountryPickerSwift (https://cocoapods.org/pods/CountryPickerSwift)。在我的一个 ViewControllers 中,添加了一个扩展来实现 CountryPicker 的协议:CountryPickerDelegate:
import CountryPicker
class PhoneCountryCodePickerViewController: UIViewController {
// ...
override func viewDidLoad() {
super.viewDidLoad()
self.countryPicker.countryPickerDelegate = self
}
// ...
}
extension PhoneCountryCodePickerViewController: CountryPickerDelegate {
func countryPhoneCodePicker(_ picker: CountryPicker, didSelectCountryWithName name: String, countryCode: String, phoneCode: String, flag: UIImage) {
NSLog ("country: \(name), countryCode: \(countryCode), phoneCode: \(phoneCode)")
}
}
在CountryPicker 代码库中,CountryPickerDelegate 定义为:
@objc public protocol CountryPickerDelegate {
func countryPhoneCodePicker(_ picker: CountryPicker, didSelectCountryWithName name: String, countryCode: String, phoneCode: String, flag: UIImage)
}
这非常简单,应该可以正常工作。
但是,当我尝试运行时,出现以下错误:
Cannot find protocol declaration for 'CountryPickerDelegate'
MyWorkProject-Swift.h
(显然我的工作项目不叫 MyWorkProject,但无论如何)。
在MyWorkProject-Swift.h 文件中我看到:
@import CountryPicker;
// ...
@class CountryPicker;
// ...
@interface PhoneCountryCodePickerViewController (SWIFT_EXTENSION(Playlist)) <CountryPickerDelegate>
- (void)countryPhoneCodePicker:(CountryPicker * _Nonnull)picker didSelectCountry:(Country * _Nonnull)country;
@end
对于我的一生,我无法弄清楚为什么会出现此错误。我已经尝试重命名 Delegate 协议以防出现一些奇怪的冲突,但这并没有帮助。
同样,所有其他 ObjC Swift 互操作性都可以正常工作。就是这个。
我知道这应该可行。
我创建了一个新项目作为示例,以证明(向我自己)它确实应该可以正常工作。以下是我使用的步骤:
- 创建了一个作为 ObjC 项目启动的项目
- 添加了一个 swift 文件来设置桥接头
- 添加了
CountryPickerSwiftcocoapod。 - 从工作项目批发中添加了
PhoneCountryCodePickerViewController(实现了有问题的CountryPickerDelegate)。
示例项目在这里:https://github.com/SuperTango/CountryPickerExample 并且工作正常。我检查了 CountryPickerExample-Swift.h 文件,就 CountryPicker 代码而言,它与工作项目“-Swift.h”文件完全相同。
我不明白为什么工作项目失败但示例项目成功。
【问题讨论】:
标签: objective-c swift xcode