我想从类的初始化动态地将闭包附加到另一个方法。例如,UIViewController
我想添加一个扩展,以便我可以在viewDidLoad
事件中注入代码。我尝试了类似下面的方法,但它不起作用:
class BaseViewController: UIViewController, MyProtocol {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Setup and bind
configure()
}
override func viewDidLoad() {
super.viewDidLoad()
// Call MyProtocol.myDidLoad but not explicitly!
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Call viewWillAppear but not explicitly!
}
}
protocol MyProtocol { }
extension MyProtocol where Self: UIViewController {
func configure() {
// Something like below isn't possible???
self.viewDidLoad += myDidLoad
self.viewWillAppear += myWillAppear
}
func myDidLoad() {
// Something
}
func myWillAppear() {
// Something
}
}
是否可以实现这一点,而无需从 ? 显式调用协议函数UIViewController
?我不想遍历我所有的类并为每个函数调用协议函数。这将是乏味的、冗余的代码,并且很容易被忽略。有没有更优雅的方式?
更新:
鉴于限制,下面是我能想到的唯一方法,但它使用继承而不是组合,并且仍然需要我显式调用协议扩展函数,这不是我想要做的:
class FirstViewController: BaseViewController {
}
class BaseViewController: UIViewController, MyProtocol, MyProtocol2, MyProtocol3 {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Configure protocols
configure(self as MyProtocol)
configure(self as MyProtocol2)
configure(self as MyProtocol3)
}
override func viewDidLoad() {
super.viewDidLoad()
// Load protocols
viewDidLoad(self as MyProtocol)
viewDidLoad(self as MyProtocol2)
viewDidLoad(self as MyProtocol3)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Prerender protocols
viewWillAppear(self as MyProtocol)
viewWillAppear(self as MyProtocol2)
viewWillAppear(self as MyProtocol3)
}
}
protocol MyProtocol { }
extension MyProtocol where Self: UIViewController {
func configure(delegate: MyProtocol) {
print("MyProtocol.configure")
}
func viewDidLoad(delegate: MyProtocol) {
print("MyProtocol.viewDidLoad")
}
func viewWillAppear(delegate: MyProtocol) {
print("MyProtocol.viewWillAppear")
}
}
protocol MyProtocol2 { }
extension MyProtocol2 where Self: UIViewController {
func configure(delegate: MyProtocol2) {
print("MyProtocol2.configure")
}
func viewDidLoad(delegate: MyProtocol2) {
print("MyProtocol2.viewDidLoad")
}
func viewWillAppear(delegate: MyProtocol2) {
print("MyProtocol2.viewWillAppear")
}
}
protocol MyProtocol3 { }
extension MyProtocol3 where Self: UIViewController {
func configure(delegate: MyProtocol3) {
print("MyProtocol3.configure")
}
func viewDidLoad(delegate: MyProtocol3) {
print("MyProtocol3.viewDidLoad")
}
func viewWillAppear(delegate: MyProtocol3) {
print("MyProtocol3.viewWillAppear")
}
}
//Output:
//MyProtocol.configure
//MyProtocol2.configure
//MyProtocol3.configure
//MyProtocol.viewDidLoad
//MyProtocol2.viewDidLoad
//MyProtocol3.viewDidLoad
//MyProtocol.viewWillAppear
//MyProtocol2.viewWillAppear
//MyProtocol3.viewWillAppear
这违背了面向协议编程的全部目的。在 iOS 开发的范围内工作时,Swift 是否可以处理一种优雅的方法,或者 POP 在这种情况下不起作用?