Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 840
Axel Guilmin Avatar asked Mar 17 '16 16:03

Axel Guilmin


People also ask

Can a protocol inherit from a class Swift?

In Swift, protocols can inherit from one or more additional protocols. Let's see how and why to use it. Here we have a User protocol, this protocol will be getting bigger each time we add a new User requirement into it.

What is nested in Swift?

In Swift, a function can exist inside the body of another function. This is called a nested function.

How many protocols can a Swift class adopt?

Since classes, structures and, enums can conform to more than one protocol, they can take the default implementation of multiple protocols. This is conceptually similar to multiple inheritance in other languages.

What is difference between protocol and class Swift?

You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.


2 Answers

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.

like image 132
GetSwifty Avatar answered Sep 20 '22 18:09

GetSwifty


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()
    }
}
like image 39
Oscar van der Meer Avatar answered Sep 17 '22 18:09

Oscar van der Meer