将Swift 3升级到4,不再在目标C中进行Swift扩展

亚伦·海曼

我刚完成将混合语言项目(objective-c和Swift)从Swift 3升级到Swift 4。

一切似乎都进行得很好,除了我的所有Swift扩展都无法在Objective-C中访问。我不知道如何使任何Swift扩展出现在Objective-C中。我已经尝试过搜索,但是除了放松private作用域之外,我几乎没有提到对Swift 4中扩展的更改

  • 所有这些扩展都可以从Swift 3的Objective-c中进行访问,因此没有不兼容的类型(结构或非原始枚举)。
  • 这些扩展标记为公开。
  • 这些扩展与Objective-C文件是同一目标的一部分,并且在同一项目中。
  • 是的,我已经在相关的objective-c文件中导入了“ ProjectName-Swift.h”。
  • 其他兼容的Swift类也会出现。似乎只是缺少扩展名。
  • 我也尝试过标记每个func公众。

例如,当我使用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扩展的声明。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章