Ric*_*hiy 7 protocols ios swift
我有两个协议:Pen和InstrumentForProfessional。我想使任何一支笔成为Professional的Instrument:
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
Run Code Online (Sandbox Code Playgroud)
use*_*434 18
协议继承
一个协议可以继承一个或多个其他协议,并且可以在它继承的需求之上添加更多的需求。协议继承的语法类似于类继承的语法,但可以选择列出多个继承的协议,用逗号分隔:
Run Code Online (Sandbox Code Playgroud)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}
}
Run Code Online (Sandbox Code Playgroud)
现在一切符合的也Pen符合InstrumentForProfessional。
这是您要求符合扩展协议的方式。
extension Pen where Self: InstrumentForProfessional {}
Run Code Online (Sandbox Code Playgroud)
当前的操作方式使编译器认为您正在进行继承,而不是协议一致性。
还要注意,let pen = ApplePen() as InstrumentForProfessional这没有意义,也不会编译。
| 归档时间: |
|
| 查看次数: |
2780 次 |
| 最近记录: |