簡體   English   中英

如何在Swift中調用動態類型的泛型函數

[英]How to call a generic function with a dynamic type in Swift

說我有一個協議Fooable

protocol Fooable {}

現在我需要在泛型函數中使用Fooable類型:

func fooingAround<FooableType: Fooable>(withType: FooableType.Type) {}

當我用Fooable類型調用函數時,這很好用:

struct Foo: Fooable {}
fooingAround(Foo.self) // works fine

但是,我需要檢索從其他地方移交給函數的Fooable類型。 這是編譯器失敗的地方:

let fooableType: Fooable.Type = // obtain from somewhere else
fooingAround(fooableType) // compiler error: "Cannot invoke 'fooingAround' with an argument list of type '(Fooable.Type)'"

具體來說,我從描述API端點的枚舉中獲取Fooable.Type ,其中每個端點由不同的Fooable類表示。

我想問題出現是因為我動態獲取了一個類型,所以在編譯時不能強類型。

有辦法解決這個問題嗎?

問題是這個:

let fooableType: Fooable.Type = // obtain from somewhere else

...正在遺忘您想要存儲在該變量中的信息,即符合Fooable的具體類型是Fooable 請考慮以下代碼編譯:

protocol Fooable {}

func fooingAround<FooableType: Fooable>(withType: FooableType.Type) {}

struct Foo: Fooable {}
fooingAround(Foo) // works fine

let foo = Foo()
let fooableType /* do not cast here */ = foo.dynamicType

fooingAround(fooableType) // also works fine

...這意味着您必須找到一種方法直接將類型信息傳遞到函數調用中而不進行強制轉換。

根據您所考慮的fooingAround的類型,您可以例如能夠沿着以下行擴展Fooable

extension Fooable {

    func fooingAround() {
        /* do some fooing with */ self.dynamicType // which is the Foo.Type when called on the `foo` value
    }
}

foo.fooingAround()

暫無
暫無

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

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