V1ru8
V1ru8

Reputation: 6147

How can I use a protocol with a typealias as a func parameter?

The following code:

protocol ProtocolA {
}

protocol ProtocolB {
    typealias T: ProtocolA
    var value : Array<T> { get set }
}

class ProtocolC {
    func method<T: ProtocolA>(value: ProtocolB<T>)
    {

    }
}

Yields these errors:

error: cannot specialize non-generic type 'ProtocolB'
func method<T: ProtocolA>(value: ProtocolB<T>)

error: generic parameter 'T' is not used in function signature
func method<T: ProtocolA>(value: ProtocolB<T>)

error: protocol 'ProtocolB' can only be used as a generic constraint because it has Self or associated type requirements
func method<T: ProtocolA>(value: ProtocolB<T>)

Can anyone explain me why this is not possible? Is this a bug or intentional?

Upvotes: 0

Views: 604

Answers (2)

rintaro
rintaro

Reputation: 51911

You cannot specialize generic protocol with <>.

Instead, you can:

func method<B: ProtocolB where B.T: ProtocolA>(value: B) {
}

That says, method accepts B where B conforms ProtocolB and its T conforms ProtocolA.

And, in this case, you don't need where B.T: ProtocolA because it's obvious.

func method<B: ProtocolB>(value: B) {
    ...
}

Upvotes: 2

NRitH
NRitH

Reputation: 13893

Remove the <T> after the B argument in the method definition. You don't need the <T: ProtocolA> in the method signature, either.

protocol ProtocolA {
}

typealias T = ProtocolA

protocol ProtocolB {
    var value : [T] { get set }
}

class ProtocolC {
    func method(value: ProtocolB)
    {

    }
}

Upvotes: 1

Related Questions