我刚刚完成了一个混合语言项目(Objective-C和Swift)从Swift 3升级到Swift 4。
除了我所有的Swift扩展在Objective-C中不再可用外,一切似乎都很顺利。我不知道如何让任何Swift扩展出现在Objective-C中。我尝试过搜索,但除了放松private
范围。
所有这些扩展都可以从swift 3中的objective-c访问,因此没有不兼容的类型(结构或非原始枚举)。
扩展名被标记为public。
这些扩展名与objective-c文件属于同一目标,位于同一项目中。
是的,我已经在相关的Objective-C文件中导入了“projectname swift.h”。
其他兼容的swift类也会出现。似乎只是缺少扩展名。
我也试过将每个func
标记为public。
例如,当我使用Swift 3时,以下扩展用于Objective-C代码:
public extension UIAlertController {
class func alert(_ title: String? = nil, message: String? = nil) -> UIAlertController {
return UIAlertController(title: title, message: message, preferredStyle: .alert)
}
@discardableResult func action(_ action: String) -> UIAlertController {
self.addAction(UIAlertAction(title: action, style: .default, handler: nil))
return self
}
@discardableResult func action(_ action: String, style: UIAlertActionStyle = .default, onSelected: ((UIAlertAction) -> Void)? = nil) -> UIAlertController {
self.addAction(UIAlertAction(title: action, style: style, handler: onSelected))
return self
}
@discardableResult func cancel(_ action: String? = "Cancel", onCancel: ((UIAlertAction) -> Void)? = nil) -> UIAlertController {
self.addAction(UIAlertAction(title: action, style: .cancel, handler: { alert in
onCancel?(alert)
}))
return self
}
@discardableResult func destructive(_ action: String, onDestruct: @escaping ((UIAlertAction) -> Void)) -> UIAlertController {
self.addAction(UIAlertAction(title: action, style: .destructive, handler: { action in
onDestruct(action)
}))
return self
}
func presentOn(_ viewController: UIViewController, animated: Bool = true) {
viewController.present(self, animated: animated, completion: nil)
}
}
最佳答案
一个非常简单的解决方案是将@objc public extension
添加到每个swift扩展的声明中。