簡體   English   中英

我該如何轉換為這樣的通用類型:MyType <ConformingX> (ConformingX是符合協議的類)

[英]How do i cast to a generic type like that: MyType<ConformingX> (ConformingX is a class that conforms to a protocol)

我將如何實現:我想使用符合協議的typeParameter強制轉換為泛型。

我嘗試了以下方法:

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>

好的,我為我的復雜案例找到了解決方案。 只需將相同的泛型添加到運行代碼的類中:

class ClassThatRunsTheCode<X> where X: SomeProtocol{

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM