altralaser altralaser - 1 month ago 19
Objective-C Question

Implementing Objective-C protocol in Swift class

I have a comprehension question. I want to use the Dropbox Objective-C framework in an iOS Swift app.

I already imported the framework successfully and set the import clause in the bridging header.

I was also able to run the authorization process so I think the framework works.

Then I try to use a component of the framework which is declared as protocol:

class ViewController: UIViewController, DBRestClientDelegate {
}


I sat the delegate property, called the loadMetadata method and implemented the corresponding event function:

let dbRestClient = DBRestClient(DBSession.shared())
dbRestClient.delegate = self
dbRestClient.loadMetadata("/")
...

func restClient(client: DBRestClient!, loadedMetadata metadata: DBMetadata!) {
}


What I'm wondering is that it seems not necessary to implement all methods of that protocol. Is this correct? In Swift implementing only a part of a protocol is enough?

I ask because the compiler displays no errors but the delegation method is never called.

Answer

Generally, in Swift you have to implement ALL methods of a protocol. (See this question about optional protocol methods: How to define optional methods in Swift protocol?)

But as you said, the framework is written in Objective-C. Objective-C supports optional methods in protocols.

@protocol ProtocolName
@required
// list of required methods
@optional
// list of optional methods
@end

Source


That's why you don't necessarily need to implement all methods declared in a protocol. Usually, only the most important methods are marked with @required, because when calling an optional method, you should always check, if the delegate implemented it.