【发布时间】:2017-09-27 08:38:10
【问题描述】:
我想使用 swift generic,如下代码所示:
func handle<T>(data: Data, with type: T.Type) {
if type is B.Type {
handleOne(data: data, with: type) //error here: In argument type 'T.Type', 'T' does not conform to expected type 'B'
// cast T comform B?
} else {
handleTwo(data: data)
}
}
func handleOne<T>(data: Data, with type: T.Type) where T:B {
}
func handleTwo(data: Data) {
}
...
protocol B {
...
}
B 是一个协议,我可以在handle 中调用handleOne 吗?可以投T comform B吗?
【问题讨论】:
-
编译器不够聪明知道
if type is B.Type是true然后类型实际上是B类型。由于B类型是handleOne函数的要求,那么这将失败! -
我不这么认为,我在Xcode9 swift4中试过,用
struct A: B {},handle(data: Data(), with: A.self),if type is B.Type会是true,你可以试试这个