The Objective-C class - accessing Swift code from Objective-C

Once the user enters their name and presses the Get Message button, we will create an instance of the Swift MessageBuilder class in the Objective-C code and call the getPersonlizedMessage() method to generate the message to be displayed.

When we access Swift code from Objective-C, we rely on an Xcode-generated header file to expose the Swift classes. This automatically generated header file declares the interface for the Swift classes. The name of this header file is the name of your project followed by - Swift.h, so the name of the header file for our project is ObjectiveCExample-Swift.h. Therefore, the first step to access the Swift code from Objective-C is to import this header file, as shown in the following line of code:

#import "ObjectiveCProject-Swift.h" 

Now that we have imported the header file to expose our Swift classes, we can use the Swift MessageBuilder class within the Objective-C code. We create an instance of the Swift MessageBuilder class exactly like we would create an instance of any standard Objective-C class. We also call the method and properties of a Swift class exactly like we would call the method and properties from an Objective-C class. The following example shows how we would create an instance of the Swift MessageBuilder class, and also how we would call the getPersonalizedMessage() method of that class:

MessageBuilder *mb = [[MessageBuilder alloc] init]; 
self.messageView.text = [mb getPersonalizedMessageWithName:@"Jon"]; 

As we can see from this code sample, Swift classes are treated as if they were Objective-C classes when we access them from Objective-C code. Once again, this allows us to access both our Objective-C and Swift types in a consistent manner.

The noticeable difference is that when we access our getPersonalizedMessage() method in our Swift code, we access it like this:

getPersonalizedMessage(name: "Jon") 

When we access it from the Objective-C code, we access it like this:

[mb getPersonalizedMessageWithName:@"Jon"]; 

Note how the message name changed to include the name parameter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset