ios - 使一个协议(protocol)符合另一个协议(protocol)

标签 ios swift protocols

我有两个协议(protocol):PenInstrumentForProfessional。我想让任何 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/

相关文章:

ios - UITableViewCell 如何自己更改 textLabel 文本?

swift - 如何模式匹配符合协议(protocol)的类型

swift - 使用 AVMetadataItem.value 快速获取媒体标题

objective-c - 前向声明错误

ios - 用户遇到与 Firestore Pod 内部 grpc::ClientAsyncReaderWriter<grpc::ByteBuffer, grpc::ByteBuffer>::Finish 相关的崩溃

ios - 带有预加载图像的 iPhone 表格 View

ios - Interface Builder 找不到任何导出或操作

swift - 在嵌入了框架的项目中找不到的框架中创建的模块

ios - 我可以将单个 NSObject 类用于多个 ViewController 类以从 API 获取数据吗

swift - Swift 4 中的多线程 for 循环