Calling Objective - C delegate method in swift - objective-c

I have a method declared in Objective-C protocol:
#protocol QMChatConnectionDelegate <NSObject>
#optional
- (void)chatServiceChatDidConnect:(QMChatService *)chatService;
I want to use this method as callback in my .swift file. My question what is difference between using chatServiceChatDidConnect method directly in class body or adding it as part of extension:
class Chat: NSObject, QMChatConnectionDelegate
{
...
func chatServiceChatDidConnect(chatService: QMChatService!) {
print("connected")
}
}
or
class Chat: NSObject, QMChatConnectionDelegate
{
...
}
extension Chat: QMChatConnectionDelegate {
func chatServiceChatDidConnect(chatService: QMChatService!) {
print("connected")
}
}
and do I need to declare it as extension Chat : QMChatConnectionDelegate {} or just extension Chat {}

There are two questions being asked here, so I'll try to address both of them as directly as possible.
What is difference between using chatServiceChatDidConnect method directly in class body or adding it as part of extension?
Depending on what you mean by "difference", the answer is either "nothing" or "very little".
Once your project is compiled, there will be no difference. During compilation, it might take slightly longer, but I doubt the difference is noticeable enough to care. During development, the difference is mostly organizational, but perhaps partly architectural.
If you do not move the extension to a separate file, the difference is going to be purely organizational. If you have a class conforming to multiple protocols or particularly large protocols, organizing the protocol conformance into extensions can be beneficial when it comes to human-parsing of the class.
If you do move the extension into a separate file, you can obtain some architectural differences as well when we consider how the private access modifier works in Swift (or also the default internal when we consider that the extension could be not just a different file, but a different module, but for simplicity sake, let's focus on private).
Consider conforming to a UITableViewDataSource protocol. Conceivably, we might want some helper methods when it comes to returning a cell from tableView(_:cellForRowAtIndexPath:), and if that's the case, tableView(_:cellForRowAtIndexPath:) is probably the only method that actually needs to call those methods. If that's the case, we can create the protocol conformance in an extension in a separate file and mark all of the helper methods as private. Now we've narrowed the scope of those helper methods to just that extension (which should be the only place that needs it).
Do I need to declare it as extension Chat: QMChatConnectionDelegate {} or just extension Chat {}?
The answer to this is it depends.
Certainly, you don't need to mark your class as conforming to a protocol in multiple places. Just one will do. And while extensions can have different access level than the class they extend (a private extension of an internal class for example), they can not have an access level broader than the class they extend (a public extension of an internal class is not allowed, for example).
What makes most sense to me is to not mark the class as conforming to the protocol but mark the extension as conforming to the protocol:
class Chat: NSObject {}
extension Chat: QMChatConnectionDelegate {}
Importantly, when we create our classes & extensions like this, it keeps our code quite modular. Our class shouldn't rely on anything in the extension. It should function entirely without it, and removing the extension allow our class to still work properly (just not for using the QMChatConnection).

First of all extension declaration is valid only from the file scope, so your second example should look like that:
class Chat: NSObject
{
...
}
extension Chat : QMChatConnectionDelegate {
func chatServiceChatDidConnect(chatService: QMChatService!) {
print("connected")
}
Secondly you shouldn't re-declare protocol conformance in both class declaration and extension.
You should treat Swift extension more or less like categories in Objective-C.
Answering your questions, there is no big difference if you declare method conforming to a protocol directly in the class scope or in the extension.
Adding protocol conformance in extensions can have several benefits:
You can add methods implementing certain protocol in a separate file
You can add protocol conformance to existing classes, without modifying their body. So in the end you can add protocol conformance to 3rd party classes
It allows for a nice logical organization of your source code.

Related

Subclassing an Objective C class using Swift in a framework target

I have a framework target in which most of the classes are written in Objective C. Recently we have started introducing Swift files in the code. We make private Objective C files available to swift code using modules(more on this can be found here).
This approach worked well until recently when I tried subclassing one of my Objective C class using Swift, I got an error in the Generated MyFramework-Swift.h file which said "Module TestSwift not found" where TestSwift is the name of the module I provided in the modulemap file. However, if I try subclassing the classes which are listed in the umbrella header of my framework(public classes), it works.
import TestSwift
#objc public class NewSwiftClass: ExistingObjectiveCClass {
//throws error in the generated MyFramework-Swift.h file while compiling
}
If I keep my swift class internal, it works
import TestSwift
#objc class NewSwiftClass: ExistingObjectiveCClass {
//works fine
}
but I would like to use this Swift class in my Objective C files hence cannot keep it internal.
TL;DR: I'm unable to subclass an existing Objective C class using Swift inside a framework target.
I believe this is impossible in Swift because it's impossible in Objective-C.
If you have a class A in your framework that is not part of your umbrella header, and you want B to subclass it and be in your umbrella header, you can't do it.
You have to declare the inheritance in your interface declaration #interface B: A, which goes in B's header and thus in the umbrella header. But the compiler is going to complain: "What is A?" You could import A's header there, but unlike Swift's import, Objective-C's #import literally drops the contents of A's header into the B header. Which means A is now in the umbrella header too i.e. public.
Mixing Swift with Objective-C isn't magic. The compiler still needs to be able to make a valid Objective-C header that accurately describes the Swift interface. So unless you can think of a way to make Objective-C do this, you can't do it in Swift.
The only alternative I can think of is to change your "is a" relationship into a "has a" relationship i.e.
#objc public class NewSwiftClass {
let parent: ExistingObjectiveCClass
}
obviously you lose most of the benefits of actual inheritance but you'll still have the parent around as a substitute for super. You could also declare a public protocol that both classes conform to to ensure that you get consistency between their methods.

Objective-C Protocol Method Name with 'To' Mangling in Swift 4

I have a .framework that I build in Objective-C and I use it in iPhone project built using Swift 4. The .framework uses a delegate to call methods as required.
I've noticed that depending on whether I use the word 'To' in my protocol method signature I get a very different implementation in Swift. For example if I define my protocol methods as:
- (void)myApiExited:(Api*)api;
- (void)myApiReadyToPresentViewController:(Api*)api;
Then in my Swift project I get:
func myApiExited(_ api:XPINApi!) {}
func myApiReady(toPresentViewController api: Api!) {}
If however I change the method signature to not include the word 'To' then the method name in the implementation becomes what I would expect it to be:
- (void)myApiReadyPresentViewController:(Api*)api;
Result:
func myApiReadyPresentViewController(_ api: Api!) {}
It is very strange to me that the word 'To' would cause this. I expect the method name in my implementation to be the same as in the protocol. Am I doing something that is wrong or is this some kind of bug.
This is by design, as the Objective-C importer picks up on conventions in Objective-C names to provide more adapted Swift names. I can't find the exhaustive set of rules, but if you want to specify a Swift name, you can use NS_SWIFT_NAME. Off the top of my head, you'd write this:
- (void)myApiReadyToPresentViewController:(Api*)api
NS_SWIFT_NAME(myApiReadyToPresentViewController(_:));

What is main reason behind use of Extensions in Objective C

I studied about extensions and now i have some queries on some points of extension use.
Point : Extensions extend the functionality of classes for which we have source code.
Query : If we already have source code for a class then we can easily write all the required methods in header file and in implementation file.So why we are using extension for this feature.
Point : Extensions also provide the alternative to private methods.
Query : we can write private methods in private interface in .m file.so why we are using extension for this feature also.
Point : Extensions makes a property readonly for other classes and readwrite for original class.
Query : this functionality also can be achieved by redefining the readonly property in implementation file with readwrite properties.
Confused with these queries, the actual concept behind the extensions.Any help would be appreciated.
The previous two answers have confused categories with class extensions, which is an easy mistake to make since Swift calls "extensions" what Objective-C calls "categories". But class extensions in Objective-C are a separate thing. As opposed to a category, which is declared like this:
#interface SomeoneElsesClass (MyCategoryName)
an Objective-C class extension is declared with nothing in the parens, like this:
#interface MyClass ()
The major differences between the two are that 1) unlike categories, an extension can only be declared for a class for which you have the source code, 2) unlike categories, which need a separate #implementation block, the implementation for anything you declare in the extension goes in the main #implementation block for the class, and 3) extensions can add stored properties, whereas categories cannot.
The primary thing extensions are used for is adding private stored properties, and extending publicly read-only properties to be writable. This can be done by other means, yes, but it requires more code. For example, a private property can be added via an extension like so:
#interface MyClass ()
#property (nonatomic, copy) NSString *someProperty;
#end
whereas to do it in the implementation, you'd have to make an ivar and then write the accessors:
#implementation MyClass {
NSString *_someIvar;
}
- (NSString *)someProperty {
return self->_someIvar;
}
- (void)setSomeProperty:(NSString *)str {
self->_someIvar = [str copy];
}
#end
As you see, the extension results in fewer lines of code, and clearer code overall. Similarly, adding read-write support to a publicly read-only property is more succinct and communicates what you want to do more clearly than writing out a setter.
Extensions can also be useful when writing library and/or framework code, because you can put an extension in an internal header file which is #imported by other source files in the framework project but not published as a public header. In this way, you can expose methods to other framework code but not to clients of the framework. In this way, you can get the same functionality that is provided by Swift's internal keyword. This can, of course, also be done with categories, but extensions provide a cleaner way to do it, since the corresponding implementation of the methods will not have to be in a separate #implementation block.
See the documentation for more information: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html#//apple_ref/doc/uid/TP40011210-CH6-SW3
My Objective-C is getting rusty, and there are subtle differences in the use of extensions in Swift, but I'll take a stab at answering your questions:
Extensions let you extend the functionality for classes for which you don't have the source code. This includes system classes.
Extensions also let you group methods into logical groupings for clarity. For example, you might create an extension that defines all the methods needed to conform to a protocol.
Yes, you can use an extension to make a property read/write inside a class and readonly for external users of the class, and you can also do that by redefining the property in the implementation. This is a matter of style. It's common to have more than one way to achieve something in programming.
If we already have source code for a class then we can easily write all the required methods in header file and in implementation file.So why we are using extension for this feature.
That is rather targeted at the classes you didn't write yourself and don't have access nor the ability to modify their source code - like UIKit or Foundation classes. Sure, you can subclass them, but if you have a fairly large codebase and want to add additional functionality to a class, then without extensions (or rather, categories in Objective-C) you'd need to rewrite your codebase to use the derived class.
we can write private methods in private interface in .m file.so why we are using extension for this feature also.
and
this functionality also can be achieved by redefining the readonly property in implementation file with readwrite properties.
That only works within the single .m file defining the class - what if you want to have readwrite access to classes properties or access to private methods within entire module (for example, a framework you're writing), but readonly outside of it, as well as not exposing the methods? Categories provide you the means for that.

Can Swift protocols be defined as dynamic?

I've converted most of my application to Swift. What's left is a number of Objective-C protocols, and some code that should use Swift idioms in place of Objective-C style.
I've done the assembly of my application using Typhoon. Now after converting one of the protocols to Swift, I noticed the intializer was no longer dynamic (required by the DI library). So I tried marking it explicitly dynamic, but got the following error:
Its complaining that the 3rd argument (my Swift protocol) can never participate as part of Objective-C. This seems like it would be a widespread limitation for Swift/ObjC interoperability. Is the only solution to define the protocol in ObjC and have the Swift classes implement that?
The following solution did not work:
public protocol WeatherReportDao : NSObjectProtocol { //Extend NSObjectProtocol
}
It seems that the best work-around is to add the #objc directive to the Swift protocol. Example:
#objc public protocol CityDao {
//etc. . .
}
. . to me, this is archaic, as what I'd really like to communicate is that the protocol requires dyanmic dispatch - something that can go beyond Swift-ObjC interoperability.
Still, it works just fine.

When are properties in a class extension added to the class in Objective C?

I was under the impression that class extensions in Objective C were just anonymous categories. However, you may add properties to these class extensions, which is impossible in categories, so I'm a bit confused:
#import "Money.h"
#interface Money ()
#property(nonatomic) NSUInteger amount;
#end
#implementation Money
#end
How are class extensions implemented? As categories? Then why are you allowed to add iVars to it? When are class extensions added to the class, in compile time or when the class is loaded?
Class extensions are a compiler mechanism that allows offsetting a subset of the instance variables, declared properties and methods declared in #interface to a specific translation unit (e.g., from a public header file to an implementation file), thus allowing header files to declare only what is supposed to be public. From the runtime perspective, extensions do not exist: everything that is declared in a class extension is merged onto the principal class. This implies that extensions must be compiled along its principal class (as opposed to categories), which you can infer from the fact that you have a single #implementation for both the principal class and its extension. It’s all part of the same class.
As you can see, class extensions are quite different from categories. Categories cannot declare instance variables, categories can reside in implementation files different from the one that implements the principal class (including classes declared and implemented in libraries) and they have their own #implementation. Furthermore, categories are explicitly loaded and attached to the principal class by the runtime.