假设我有一个名为 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
类表示。我想问题出在我是动态获取类型,所以在编译时无法进行强类型检查。
有没有什么方法可以解决这个问题?