Swift type of general type, corresponding to two protocols

I have a generic method in one of my classes where I want to have a generic type corresponding to UIViewController and UIPickerViewDelegate . How can i do this? I thought about it:

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

But this code does not recognize UIPickerViewDelegate . I also thought of using a handset | instead of a comma, but it's even worse, the compiler does not accept this. Is it possible to do this or do I need to make 2 parameters for the class and protocol? Or is there a more convenient solution?

Thanks for your help and Merry Christmas:]

+8
source share
3 answers

Your code:

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

declares parameters 2 :

  • T , which is equal to the UIViewController . And it is used as the type of the parameter viewController .
  • UIPickerViewDelegate , which is Any . And it is not used.

Instead, you should use "Where Clause" , for example:

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

In Swift 4, everything has changed: func foo<T: UIViewController> (viewController: T) where T:UIPickerViewDelegate {}

+4
source

Starting with Swift 4, you can use the protocol compilation features. Here you go:

 func foo<T: UIViewController & UIPickerViewDelegate> (viewController: T) {} 
0
source

Source: https://habr.com/ru/post/980113/


All Articles