我有两个协议: Pen和InstrumentForProfessional。我想让任何一支钢笔成为InstrumentForProfessional
protocol Pen {
var title: String {get}
var color: UIColor {get}
}
protocol Watch {} // Also Instrument for professional
protocol Tiger {} // Not an instrument
protocol InstrumentForProfessional {
var title: String {get}
}
class ApplePen: Pen {
var title: String = "CodePen"
var color: UIColor = .blue
}
extension Pen: InstrumentForProfessional {} // Unable to make ApplePen an Instument for Professional: Extension of protocol Pen cannot have an inheritance clause
let pen = ApplePen() as InstrumentForProfessional发布于 2018-06-21 11:22:53
协议继承 协议可以继承一个或多个其他协议,并可以在其继承的需求之上添加进一步的需求。协议继承的语法类似于类继承的语法,但可以选择列出由逗号分隔的多个继承协议: 协议InheritingProtocol: SomeProtocol,AnotherProtocol { //协议定义在这里}
所以,你基本上需要这样做:
protocol InstrumentForProfessional {
var title: String {get}
}
protocol Pen: InstrumentForProfessional {
var title: String {get} // You can even drop this requirement, because it's already required by `InstrumentForProfessional`
var color: UIColor {get}
}现在,所有符合Pen的东西也都符合InstrumentForProfessional。
发布于 2018-06-21 10:49:01
下面是如何在扩展中要求符合协议的方法。
extension Pen where Self: InstrumentForProfessional {}当前您所做的方式使编译器认为您正在进行继承,而不是协议一致性。
还请注意,let pen = ApplePen() as InstrumentForProfessional没有意义,也不会编译。
发布于 2020-07-05 05:39:08
我想如果你看看这个答案,它解决了同样的问题。
https://stackoverflow.com/a/37353146/1070718
@纸质1111接近你想要的内容,但我认为你真的很想这么做:
extension InstrumentForProfessional where Self: Pen {}因为钢笔已经符合InstrumentForProfessional,所以当它是钢笔时,您只需要扩展InstrumentForProfessional。
有时,我忘记了在Swift中协议继承是如何工作的,但这多亏了它来刷新我的记忆。
https://stackoverflow.com/questions/50966560
复制相似问题