Swift Covariant Generics

前端 未结 1 869
终归单人心
终归单人心 2021-01-18 06:35

Here is an example of what I\'d like to achieve:

protocol SomeType {}

class SomeClass: SomeType {}

struct SomeGenericStruct {
    typealias E = A
         


        
相关标签:
1条回答
  • 2021-01-18 06:53

    You can use generic method for this:

    func take<T where T: SomeType>(someType: SomeGenericStruct<T>) { }
    

    The only problem with this is that you can not pass SomeGenericStruct<SomeType> to it. It must be a generic of some concrete type instead. If totally necessary, you can just have two functions doing the same thing essentially:

    func take(someInput: SomeGenericStruct<SomeType>) { /* do stuff */ }
    func take<T where T: SomeType>(someType: SomeGenericStruct<T>) { /* do same stuff */ }
    
    0 讨论(0)
提交回复
热议问题