简体   繁体   中英

How to extend a protocol in Swift

In Swift, how do we define a protocol that extends or specializes a base protocol? The documentation does not seem to make this clear.

Also unclear, do Swift protocols conform to/extend the NSObject protocol? This is an interesting question as it would hint at whether Swift uses vtable- or message-based dispatch for calling protocol methods.

Protocol inheritance uses the regular inheritance syntax in Swift.

protocol Base {
    func someFunc()
}

protocol Extended : Base {
    func anotherFunc()
}

Swift Protocols do not by default conform to NSObjectProtocol. If you do choose to have your protocol conform to NSObjectProtocol, you will limit your protocol to only being used with classes.

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.

protocol SomeOtherProtocol: SomeProtocol, NSObjectProtocol { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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