0

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 ?

  • Can you elaborate what do you mean by *to be called automatically if any class or struct has conformed to the protocol*. You can call it anywhere if that class conforms to this `protocol`. – Kamran Sep 24 '19 at 04:38
  • @Kamran I want `addLanguageChangeObserver` to be called automatically by `SecondViewController` after it conforms. I dont want to call it explicitly with object. I think this is same when conforming with Equatable protocol. – ex-tension Sep 24 '19 at 05:18
  • It can not be called automatically. You have to call it inside `init` or `viewDidLoad` so that you can get change notification. – Kamran Sep 24 '19 at 05:21
  • @Kamran how do you approach this kind of scenario? Do you call the method in every ViewControllers that conforms with the protocol to observe the change? Or Just put in `BaseViewController`. – ex-tension Sep 24 '19 at 05:30

0 Answers0