Reputation: 11
I am trying to invoke a method of a protocol extension if a class/struct has conformed to the protocol.
The main reason is to not write the same code everywhere to perform some simple register/deinit operations.
protocol LanguageChangeDipatcher {
func postLanguageChangeNotification()
}
extension LanguageChangeDipatcher {
func postLanguageChangeNotification() {
NotificationCenter.default.post(name:.languageChange, object: nil)
}
}
@objc protocol LanguageChangeObserver: NSObjectProtocol {
func onLanguageChange()
}
extension LanguageChangeObserver {
func addLanguageChangeObserver() {
NotificationCenter.default.addObserver(self, selector: #selector(onLanguageChange), name: .languageChange, object: nil)
}
}
class SecondViewController: UIViewController, LanguageChangeObserver {
}
I expect the addLanguageChangeObserver to be called automatically if any class or struct has conformed to the protocol. Is it possible in Swift programming language ?
Upvotes: 1
Views: 344