swiftswift-protocols

Swift protocol nested in a class


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 ?


Solution

  • Swift 5.10 Update

    From Swift 5.10 you can now nest protocols inside non-generic class, actor, enum or struct.

    reference >here<

    class ButtonView {
        protocol Delegate: AnyObject {
            func didTap(_ button: ButtonView)
        }
    
        weak var delegate: Delegate?
    
        func tapAction() {
          delegate?.didTap(self)
        }
    }
    
    class ViewModel: ButtonView.Delegate {
        func didTap(_ button: ButtonView) {
            print("\(button) tapped.")
        }
    }