Swift Xcode 7 beta 5 type cannot refer to itself as a requirement

爱⌒轻易说出口 提交于 2019-12-23 17:40:15

问题


This code used to be legal:

protocol Flier {
    typealias Other : Flier
    func flockTogetherWith(f:Other)
}
struct Bird : Flier {
    func flockTogetherWith(f:Insect) {}
}
struct Insect : Flier {
    func flockTogetherWith(f:Insect) {}
}

Now (in Xcode 7 beta 5) it's not. What's going on here? Is this a bug? I am merely trying to ensure that adopters of Flier declare flockTogetherWith with a parameter that is some adopter of Flier. I've always been able to do that. Why is it suddenly wrong to do?


回答1:


I have no idea why this should be wrong. But it's fairly easy (though annoying) to work around it: declare another protocol for Flier to adopt and use that as the constraining type:

protocol Superflier {}
protocol Flier : Superflier {
    typealias Other : Superflier
    func flockTogetherWith(f:Other)
}

It makes the code really tortured but at least it gets it past the compiler.

EDIT: Response on the dev forum from SevenTenEleven:

Having this kind of constraint isn't inherently unreasonable, but in some cases it would lead to compiler crashes. We decided to lock down on this for now. Your workaround of using a second protocol is a reasonable one.

So the change is probably to be regarded as deliberate if regrettable, and the workaround I've given is the way to go for now.



来源:https://stackoverflow.com/questions/31869440/swift-xcode-7-beta-5-type-cannot-refer-to-itself-as-a-requirement

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