[英]How do i cast to a generic type like that: MyType<ConformingX> (ConformingX is a class that conforms to a protocol)
how would i achieve this: I want to cast to a generic type with a typeParameter that conforms to a protocol. 我将如何实现:我想使用符合协议的typeParameter强制转换为泛型。
I tried the following: 我尝试了以下方法:
let castedMyType = notCastedMyType as? MyType<X>
let castedMyType = notCastedMyType as? MyType<X> where X: SomeProtocol
let castedMyType = notCastedMyType as? MyType<X where X: SomeProtocol>
let castedMyType = notCastedMyType as? MyType<X: SomeProtocol>
But nothing works. 但是没有任何效果。
Here is some example code to get you up and running. 这是一些示例代码,可帮助您入门和运行。 Just put it in a Playground:
只需将其放在操场上即可:
import Foundation
protocol SomeProtocol{}
class X{}
// example class that conforms to the protocol
class ConformingX: SomeProtocol{}
class BaseType{}
class MyType<X>: BaseType where X: SomeProtocol{}
let notCastedMyType: BaseType = MyType<ConformingX>()
// not working
let castedMyType = notCastedMyType as? MyType<X>
let castedMyType = notCastedMyType as? MyType<X> where X: SomeProtocol
let castedMyType = notCastedMyType as? MyType<X where X: SomeProtocol>
let castedMyType = notCastedMyType as? MyType<X: SomeProtocol>
Ok I found a solution for my complex case. 好的,我为我的复杂案例找到了解决方案。 Just add the same generic to the class that is running the code:
只需将相同的泛型添加到运行代码的类中:
class ClassThatRunsTheCode<X> where X: SomeProtocol{
func executingFunc(){
// working
let castedMyType = notCastedMyType as? MyType<X>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.