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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With