[英]Can cast T to comform a protocol in swift
我想使用swift通用代码,如下所示:
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
符合B
吗?
确实没有必要将类型作为参数传递,因为可以从对象本身中检索它。 is
类型检查运算符适用于对象实例,并检查类型名称:
protocol A {}
protocol Data {}
func handle (data: Data) {
if data is A {
print("Handled A.")
} else {
print("Handled something else.")
}
}
struct AStruct: Data, A {}
handle(data: AStruct()) // Handled A.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.