以下Swift代码:
class Workflow<ItemClass: Hashable> {
var block: (ItemClass -> Int)?
init() {}
}
protocol ProtocolX {
typealias ItemClass
func foo(x: ItemClass) -> Int
}
func test<Y: ProtocolX, ItemClass: Hashable>(protX: Y, x: ItemClass) {
let workflow = Workflow<ItemClass>()
workflow.block = { (x: ItemClass) in
return protX.foo(x)
}
}此编译器错误失败:
Cannot invoke 'foo' with an argument list of type '(ItemClass)':
Expected an argument list of type '(Self.ItemClass)'在代码片段return protX.foo(x)中。
这似乎是一个人为的例子,但它从一个现实世界的问题,我正在减少。
如果我尝试遵循错误消息中的建议,我只会得到:
'Self' is only available in a protocol or as the result of a method in a class;
did you mean 'Test'?我怎么才能把这个打出来?
发布于 2016-02-05 22:19:08
您没有理由让编译器相信Workflow.ItemClass与函数test(_:x:)中的ProtocolX.ItemClass是相同的类型。如果您的意思是要求test函数的test类型参数与函数中的ProtocolX.ItemClass相同,您可以告诉编译器需要它,如下所示:
func test<Y: ProtocolX, ItemClass: Hashable where Y.ItemClass == ItemClass>(protX: Y, x: ItemClass) {
let workflow = Workflow<ItemClass>()
workflow.block = { (x: ItemClass) in
return protX.foo(x)
}
}但是,您可以完全消除单独的ItemClass参数:
func test<Y: ProtocolX where Y.ItemClass: Hashable>(protX: Y, x: Y.ItemClass) {
let workflow = Workflow<Y.ItemClass>()
workflow.block = { (x: Y.ItemClass) in
return protX.foo(x)
}
}https://stackoverflow.com/questions/35234473
复制相似问题