How to extend a protocol in Swift

Jasper Blues picture Jasper Blues · Sep 9, 2014 · Viewed 15k times · Source

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.

Answer

Connor picture Connor · Sep 9, 2014

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.