【问题标题】:Swift: Specializing method implementation with protocol extensionsSwift:使用协议扩展专门化方法实现
【发布时间】:2018-08-21 20:50:11
【问题描述】:

提供一些上下文:

P 代表属性。代码的目的是不同类型的值应该由单独的方法(例如 serializeInt、serializeDouble 等)处理,类似于方法重载,但参数的类型来自类型参数。

下面的代码实际上运行良好。它调用专门的 pr(_: Int) 实现并打印“int”。

但如果我将声明“func pr(_ t: Int)”更改为注释掉的“func pr(_ t: T)”,则调用通用版本。

任何人都有任何指向此行为的指定位置或为什么会这样工作的指针?

  protocol P {
     associatedtype T
     // this will be 'specialized' for concrete types
     func pr(_ t: T)

     // the operation that should call different pr implementations depending on T
     func op(_ t: T)
  }

  extension P {
     func op(_ t: T) {
        pr(t)
     }
  }

  // fallback implementation
  extension P {
     func pr(_ t: T) {
        print("generic")
     }
  }

  // pr 'specialized' on Int
  extension P where T == Int {
     //   func pr(_ t: T) {
     func pr(_ t: Int) {
        print("int")
     }
  }


  struct Prop<T>: P {
  }

  // create an Int prop and do the op
  let p = Prop<Int>()

  p.op(1)

【问题讨论】:

  • 遇到同样的问题。有什么解决办法吗?
  • 我的困惑来自于没有意识到 T 泛型参数和关联的类型 T 不是一回事。至于我遇到的具体问题,我结束了定义另一个协议“SettingsBacked”并使标准类型符合它。

标签: ios swift generics protocols swift-extensions


【解决方案1】:

没有看到任何奇怪的行为。如果您取消注释此行 – func pr(_ t: T) {

这里p.op(1) 将调用默认方法,因为您还没有提供op 方法where T == Int 的实现。而默认op 调用默认pr 这就是它打印“通用”的原因。

【讨论】:

  • 我的意思是如果代码变成:extension P where T == Int { func pr(_ t: T) { print("int") } } 那么它就停止被调用
猜你喜欢
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多