Chr*_*nce 5 generics protocols swift
In Swift, I've got a protocol like this:
protocol P {
associatedtype T
func f(val:T)
}
Run Code Online (Sandbox Code Playgroud)
I want to define a class like this:
class B<X:P> {
}
Run Code Online (Sandbox Code Playgroud)
And then use the associatedtype T within the class B.
I've tried this:
class B<X:P> {
var v:T // compiler says "Use of undeclared type"
init() {
}
}
Run Code Online (Sandbox Code Playgroud)
I've also tried this:
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)'
}
}
Run Code Online (Sandbox Code Playgroud)
Any suggestions?
T是占位符类型的关联类型X,因此您将其引用为X.T。例子:
class B<X: P> {
var v: X.T
init(v: X.T) {
self.v = v
}
func g(x: X) {
x.f(val: v)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1102 次 |
| 最近记录: |