Swift:使用协议扩展实现专用方法



提供一些上下文:

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)

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

在这里p.op(1)将调用默认方法,因为您尚未为op方法where T == Int提供实现。默认op调用默认pr这就是它打印"通用"的原因。

最新更新