【问题标题】:Can cast T to comform a protocol in swift可以快速转换 T 以符合协议
【发布时间】: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.Typetrue然后类型实际上是B类型。由于 B 类型是 handleOne 函数的要求,那么这将失败!
  • 我不这么认为,我在Xcode9 swift4中试过,用struct A: B {}handle(data: Data(), with: A.self)if type is B.Type会是true,你可以试试这个

标签: swift generics casting


【解决方案1】:

实际上没有必要将类型作为参数传递,因为它可以从对象本身中检索。 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.

【讨论】:

  • 在我的问题中,handleOne 需要参数.Type
  • 这应该可以工作:func handle&lt;T: Data&gt;(data: T) { if data is A { handleOne(data: data, with: type(of: data)) } else { print("Handled something else.") } }
  • 你也可以使用 T.self 代替 type(of: data)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多