【发布时间】: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