繁体   English   中英

在Swift中,如何在类型参数受协议约束的泛型类中使用关联类型?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM