Swift protocol nested in a class

Viewed 11620

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 ?

3 Answers

this is my work around:

protocol MyViewControllerDelegate : class {
    func eventHappened()
}

class MyViewController : UIViewController {
    typealias Delegate = MyViewControllerDelegate
    weak var delegate: Delegate?
    
    private func myFunc() {
        delegate?.eventHappened()
    }
}
Related