提供一些上下文:
P 代表属性(property)。代码的目的是不同类型的值应该由单独的方法(例如 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
这就是它打印“generic”的原因。
关于ios - Swift:使用协议(protocol)扩展专门化方法实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51956521/