The protocol extension is one of the new things from Swift 2.0. This allows you to determine the behavior of the protocol itself. If you performed the method definition in both the confirming class and in the extension of your protocol, the implementation of the method in the confirming class will be called at run time. But the optional protocol is actually a by-product of goal c. This means that if you want to define an optional protocol in swift, you need to insert the @objc attribute before declaring the protocol. When I experimented with protocol extension, as you explained, it works well when the protocol is not optional. But when the protocol is optional, the application broke up. CLLocationManagerDelegate delegate methods are declared optional. I think this may be the reason.
view controller 1
class ViewController: UIViewController,MyViewControllerProtocol { var myViewController:NewViewController? override func viewDidLoad() { super.viewDidLoad() let sb = UIStoryboard(name: "Main", bundle: nil) myViewController = sb.instantiateViewControllerWithIdentifier("newViewController") as? NewViewController myViewController?.delegate = self myViewController?.view.frame = self.view.bounds self.view.addSubview((myViewController?.view)!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func newViewControllerLoaded(){ print("protocol definition called inside class") } } protocol MyViewControllerProtocol: NewViewControllerProtocol { func newViewControllerLoaded() } extension MyViewControllerProtocol{ func newViewControllerLoaded(){ print("protocol definition called inside extension") } }
View Controller 2
protocol NewViewControllerProtocol { func newViewControllerLoaded() } class NewViewController: UIViewController { var delegate: NewViewControllerProtocol? override func viewDidLoad() { delegate?.newViewControllerLoaded() } }
with protocol implementation in ViewController
protocol definition called inside class
after removing the protocol implementation from ViewController
protocol definition called inside extension
One way to fix your problem is to apply the extension to your class, then the protocol implementation will be inside your class. But this is not an extension of the protocol.
extension ViewController /*where Self: UIViewControll*/ { // Tried using where clause but still no go :( // Not being triggered by CLLocationManagerDelegate! :( // Move to ViewController class and error goes away func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("MyLocationProtocol: locationManager: didUpdateLocations") } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("MyLocationProtocol: locationManager: didFailWithError") } }
source share