嗨 =)我刚遇到一个设计问题,需要(本质上)执行以下操作:
我想在任何符合协议MyProtocol
的UIViewController
子类的viewWillAppear:
上注入一些代码。 代码解释如下:
protocol MyProtocol
{
func protocolFunction() {
//do cool stuff...
}
}
extension UIViewController where Self: MyProtocol //<-----compilation error
{
public override class func initialize()
{
//swizzling stuff switching viewWillAppear(_: Bool) with xxx_viewWillAppear(animated: Bool)
}
// MARK: - Swizzling
func xxx_viewWillAppear(animated: Bool)
{
self.xxx_viewWillAppear(animated)
//invoke APIs from
self.protocolFunction() // MyProtocol APIs
let viewLoaded = self.isViewLoaded // UIViewController APIs
}
}
主要问题在于我需要在UIVIewController
扩展中做两件事情:
- 调用
MyProtocol
和UIViewController
API - 覆盖
UIViewController
方法initialize()
,以便能够交换viewWillAppear:
- 我们不能使用条件来扩展类(即
extension UIViewController where Self: MyProtocol
) - 如果我们扩展协议,我们可以添加条件
extension MyProtocol where Self: UIViewController
,但我们不能在协议扩展中覆盖来自类的方法,这意味着我们无法public override class func initialize()
进行交换所需的操作。
谢谢您的帮助!