Fogmeister Fogmeister - 2 months ago 18
Swift Question

Swift protocol for UIViewController subclasses

Is it possible to declare a protocol and also define the type of object that can conform to it?

I have a set of closures that I'd like to configure in various different subclasses of

UIViewController
in my project. (They are all related).

I'd like to have a factory function that creates the correct type of
UIViewController
subclass but then returns it as a protocol type.

That way I can then configure the various closures and push the view controller onto the navigation controller.

I can either...

Return the
UIViewController
superclass and push it onto the navigation stack but then not be able to set the closures properly as the compiler doesn't know it conforms to the protocol.

or...

Return the protocol type and I'm able to set the closures properly but then the compiler doesn't know that it's a
UIViewController
subclass so I can't push it onto the navigation controller.

Is there a way to do both?

Thanks

Answer

In Objective C you were able to declare a variable like this:

UIViewController <Protocol> *variable;

Unfortunately, this is not possible with Swift, which considering how protocol-oriented Swift is, it's very strange.

This is pretty uncomfortable because like you found out, the compiler can't be aware of both the class and the protocol at the same time, so you have to cast twice, you have to check that the object is of the allowed class at runtime, and have to document it in your code to prevent people from sending the wrong kind of object.