繁体   English   中英

可以快速将T转换成协议

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM