正在将 Swift 3 升级到 4,swift 扩展不再在 objective c 中

Upgrading Swift 3 to 4, swift extension no longer in objective c

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

除了我的所有 Swift 扩展在 objective-c 中不再可用外,一切似乎都很顺利。我不知道如何让 any Swift 扩展显示在 objective-c 中。我试过搜索,但除了放宽 private 范围外,我找不到任何关于 Swift 4 中扩展名更改的提及。

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