Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 846
Jasper Blues Avatar asked Sep 09 '14 00:09

Jasper Blues


2 Answers

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.

like image 106
Connor Avatar answered Sep 19 '22 13:09

Connor


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 { } 
like image 40
Mick MacCallum Avatar answered Sep 19 '22 13:09

Mick MacCallum