简体   繁体   中英

In Swift, How do I use an associatedtype in a Generic Class where the type parameter is constrained by the protocol?

In Swift, I've got a protocol like this:

protocol P {
    associatedtype T
    func f(val:T)
}

I want to define a class like this:

class B<X:P> {
}

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() {
    }
}

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)'
    }
}

Any suggestions?

T is the associated type of the placeholder type X , so you reference it as XT . Example:

class B<X: P> {
    var v: X.T

    init(v: X.T) {
        self.v = v
    }

    func g(x: X) {
        x.f(val: v)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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