ex-tension
ex-tension

Reputation: 11

Is there a way to automatically invoke a protocol method after conformance in Swift?

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

Answers (0)

Related Questions