Make a protocol conform to another protocol

前端 未结 4 1361
臣服心动
臣服心动 2021-02-12 11:57

I have two protocols: Pen and InstrumentForProfessional. I\'d like to make any Pen to be an InstrumentForProfessional:

protoc         


        
4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 12:43

    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
    }
    

    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}
    }
    

    Now everything that conforms to Pen conforms to InstrumentForProfessional too.

提交回复
热议问题