Swift protocol nested in a class

Axel Guilmin picture Axel Guilmin · Mar 17, 2016 · Viewed 9.6k times · Source

I would like to nest a protocol in my class to implement the delegate pattern like so :

class MyViewController : UIViewController {

    protocol Delegate {
        func eventHappened()
    }

    var delegate:MyViewController.Delegate?

    private func myFunc() {
        delegate?.eventHappened()
    }
}

But the compiler will not allow it :

Protocol 'Delegate' cannot be nested inside another declaration

I can easily make it work by declaring MyViewControllerDelegate outside of the class scope.
My question is why such a limitation ?

Answer

GetSwifty picture GetSwifty · Mar 17, 2016

according to the swift documenation

Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support.

Given protocols are not on that list, it doesn't appear that it's currently supported. It's possible they will add the feature at some point, (Swift was announced less than 2 years go after all). Any idea on why they won't or haven't would be speculation on my part.