符合两种协议的Swift通用类型 [英] Swift generic type conforming to two protocols
问题描述
我在我的类中有一个泛型方法,我想要一个符合 UIViewController
和 UIPickerViewDelegate $ c $的泛型类型C>。我怎样才能做到这一点?我想这样做:
func foo< T:UIViewController,UIPickerViewDelegate> (#viewController:T){}
但是这段代码不能识别 UIPickerViewDelegate
。我还想过使用管道 |
而不是逗号,但这更糟糕,编译器不接受。
是否可以这样做,还是必须为类和协议做2个参数?或者是否有更好的解决方法?
感谢您的帮助和圣诞快乐:] / div>
您的代码:
func foo< T:UIViewController,UIPickerViewDelegate> (#viewController:T){}
声明 2 泛型参数:
-
T
它是UIViewController
。它被用作viewController
参数类型。 -
UIPickerViewDelegate
它是不限
。
相反,您应该使用Where Clause,如:
func foo< T:UIViewController where T:UIPickerViewDelegate> (#viewController:T){}
I have a generic method in one of my classes where I want to have a generic type conforming to UIViewController
and UIPickerViewDelegate
. How can I do that? I thought of doing this:
func foo<T: UIViewController, UIPickerViewDelegate> (#viewController: T) {}
But this code doesn't "recognize" the UIPickerViewDelegate
. I also thought of using the pipe |
instead of the comma but this is even worse, the compiler doesn't accept that.
Is it possible to do this or do I have to do 2 parameters for the class and the protocol? Or is there a nicer workaround?
Thanks for your help and Merry Christmas :]
Your code:
func foo<T: UIViewController, UIPickerViewDelegate> (#viewController: T) {}
declares 2 generics parameters:
T
which isUIViewController
. And it's used asviewController
parameter type.UIPickerViewDelegate
which isAny
. And it's not used.
Instead, you should use "Where Clause", like:
func foo<T: UIViewController where T:UIPickerViewDelegate> (#viewController: T) {}
这篇关于符合两种协议的Swift通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!