我有两个协议(protocol):Pen 和 InstrumentForProfessional。我想让任何 Pen 成为 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
最佳答案
Protocols can inherit each other :
Protocol Inheritance
A protocol can inherit one or more other protocols and can add further requirements on top of the requirements it inherits. The syntax for protocol inheritance is similar to the syntax for class inheritance, but with the option to list multiple inherited protocols, separated by commas:
protocol InheritingProtocol: SomeProtocol, AnotherProtocol { // protocol definition goes here }
所以,您基本上需要这样做:
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
。
关于ios - 使一个协议(protocol)符合另一个协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50966560/