本文介绍了使一个协议符合另一个协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个协议: InstrumentForProfessional .我想将任何 Pen 设置为 InstrumentForProfessional :

I have two protocols: Pen and InstrumentForProfessional. I'd like to make any Pen to be an 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

推荐答案

协议可以互相继承:

protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
    // protocol definition goes here
}

因此,您基本上需要执行以下操作:

So, you basically need to do this:

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 .

Now everything that conforms to Pen conforms to InstrumentForProfessional too.

这篇关于使一个协议符合另一个协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:02