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

巧了我就是萌 提交于 2019-12-23 06:01:14

问题


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?


回答1:


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



回答2:


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

    }
}


来源:https://stackoverflow.com/questions/32238469/how-can-i-use-a-protocol-with-a-typealias-as-a-func-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!