我如何转换为这样的通用类型:MyType <conformingx>(ConformingX是符合协议的类)

时间:2018-11-08 00:44:12

标签: swift generics protocols

我将如何实现:我想将类型参数转换为符合协议的泛型类型。

我尝试了以下操作:

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>

但没有任何效果。

这是一些示例代码,可帮助您入门和运行。只需将其放在操场上即可:

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>

1 个答案:

答案 0 :(得分:0)

好的,我为我的复杂案件找到了解决方案。只需将相同的泛型添加到运行代码的类中即可:

class ClassThatRunsTheCode<X> where X: SomeProtocol{

    func executingFunc(){
        // working
        let castedMyType = notCastedMyType as? MyType<X>
    }
}