![](/img/trans.png)
[英]How do I implement a Swift protocol with a generic constrained type property?
[英]In Swift, How do I use an associatedtype in a Generic Class where the type parameter is constrained by the protocol?
在Swift中,我有一个像这样的协议:
protocol P {
associatedtype T
func f(val:T)
}
我想定义一个这样的类:
class B<X:P> {
}
然后在类B中使用associatedtype
T。
我已经试过了:
class B<X:P> {
var v:T // compiler says "Use of undeclared type"
init() {
}
}
我也尝试过这个:
class B<X:P, Y> {
typealias T = Y
var v:T
init() {
}
func g(val:X) {
val.f(val: v) // compiler says "Cannot invoke 'f' with an argument list of type '(val:Y)'
}
}
有什么建议么?
T
是占位符类型X
的关联类型,因此您将其称为XT
。 例:
class B<X: P> {
var v: X.T
init(v: X.T) {
self.v = v
}
func g(x: X) {
x.f(val: v)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.