符合两种协议的Swift通用类型 [英] Swift generic type conforming to two protocols

查看:123
本文介绍了符合两种协议的Swift通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的类中有一个泛型方法,我想要一个符合 UIViewController UIPickerViewDelegate 。我怎样才能做到这一点?我想这样做:

  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 is UIViewController. And it's used as viewController parameter type.
  • UIPickerViewDelegate which is Any. And it's not used.

Instead, you should use "Where Clause", like:

func foo<T: UIViewController where T:UIPickerViewDelegate> (#viewController: T) {}

这篇关于符合两种协议的Swift通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆