Swift protocol for UIViewController subclasses

我们两清 提交于 2019-12-23 18:07:51

问题


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


回答1:


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.




回答2:


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{ }


来源:https://stackoverflow.com/questions/39596262/swift-protocol-for-uiviewcontroller-subclasses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!