简体   繁体   中英

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

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.

Yes you can! Do it like this..

// a protocol to make sure the the conforming object is subclass of UIViewController

public protocol IamViewController { }

//make every UIViewController  adopt the IamViewController protocol

extension UIViewController:IamViewController { }

//create your protocol and add a requirement that it must be UIViewController if it want to conform to it

protocol vcObject:IamViewController{ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM