I've read so many articles about classes and protocols but still didn't found a solution. May be I just didn't understand all of them.
So there's a simple protocol (removed some parts not relevant to the problem):
protocol InfoObject : NSObjectProtocol
{
var statusImage: UIImage? {get}
func viewControllerForItemIndex(_ index: Int?) -> UIViewController?
}
But I would like the function viewControllerForItemIndex
not only return an object of type UIViewController?
but it should conform to the protocol InfoObjectDisplaying
(not shown here) as well.
In Objective-C I would write:
- (UIViewController<InfoObjectDisplaying>*)viewControllerForItemIndex:(NSInteger) index;
Is this possible in swift?
First off, you don't need to inherit from NSObjectProtocol
in Swift :)
And no, you can't do this directly in Swift. You can require that an object conforms to a protocol or a class, but not both. However, you can declare viewControllerForItemIndex
as a generic function and require that its type parameter conforms to specific requirements:
func viewControllerForItemIndex<T: UIViewController where T: InfoObjectDisplaying>(_ index: Int?) -> T?
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments