说我有一个协议(protocol)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的具体类型是什么。考虑以下代码可以编译:
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()

关于swift - 如何在Swift中使用动态类型调用泛型函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36339976/

10-10 20:53
查看更多