Swift协变泛型
问题描述:
以下是我想达到的一个例子:
Here is an example of what I'd like to achieve:
protocol SomeType {}
class SomeClass: SomeType {}
struct SomeGenericStruct<A> {
typealias E = A
}
func take(someType: SomeGenericStruct<SomeType>) {}
let concreteGenericStruct1: SomeGenericStruct<SomeType> = SomeGenericStruct<SomeType>()
let concreteGenericStruct2: SomeGenericStruct<SomeClass> = SomeGenericStruct<SomeClass>()
take(concreteGenericStruct1)
take(concreteGenericStruct2) // much no work, very repair. wow.
甚至更简单:
Or even simpler:
let concreteGenericStruct3: SomeGenericStruct<SomeType> = SomeGenericStruct<SomeClass>() as SomeGenericStruct<SomeType> // still no work
我如何设法提供 take
with concreteGenericStruct2
?
How can I manage to provide take
with concreteGenericStruct2
?
答
为此:
You can use generic method for this:
func take<T where T: SomeType>(someType: SomeGenericStruct<T>) { }
唯一的问题是您无法传递 SomeGenericStruct< SomeType>
。它必须是一个具体类型的泛型。如果完全有必要的话,你可以只有两个函数做同样的事情:
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 */ }