简体   繁体   English

如何在Swift中扩展协议

[英]How to extend a protocol in Swift

In Swift, how do we define a protocol that extends or specializes a base protocol? 在Swift中,我们如何定义扩展或专门化基本协议的协议? The documentation does not seem to make this clear. 文档似乎没有说清楚。

Also unclear, do Swift protocols conform to/extend the NSObject protocol? 还不清楚,Swift协议是否符合/扩展NSObject协议? This is an interesting question as it would hint at whether Swift uses vtable- or message-based dispatch for calling protocol methods. 这是一个有趣的问题,因为它会暗示Swift是否使用vtable或基于消息的调度来调用协议方法。

Protocol inheritance uses the regular inheritance syntax in Swift. 协议继承使用Swift中的常规继承语法。

protocol Base {
    func someFunc()
}

protocol Extended : Base {
    func anotherFunc()
}

Swift Protocols do not by default conform to NSObjectProtocol. 默认情况下,Swift协议不符合NSObjectProtocol。 If you do choose to have your protocol conform to NSObjectProtocol, you will limit your protocol to only being used with classes. 如果确实选择使协议符合NSObjectProtocol,则会将协议限制为仅用于类。

The syntax is the same as if you were declaring a class that inherited from a superclass. 语法与声明从超类继承的类相同。

protocol SomeProtocol { }

protocol SomeOtherProtocol: SomeProtocol { }

And no, they do not. 不,他们没有。 If you want your protocol to conform to NSObjectProtocol as well, you can supply multiple protocols for your new protocol to conform to like this. 如果您希望协议也符合NSObjectProtocol,您可以为新协议提供多种协议以符合这样的要求。

protocol SomeOtherProtocol: SomeProtocol, NSObjectProtocol { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM