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

The Swift MessageBuilder class will contain one method named getPersonalizedMessage(). This method will use the getMessage() method from the Objective-C Messages class to retrieve a message and will then customize that message prior to returning it to the function that called it. Here is the code for the Swift MessageBuiler class:

import Foundation 
 
class MessageBuilder: NSObject { 
  func getPersonalizedMessage(name: String) -> String {  
    let messages = Messages() 
    let retMessage = "To: " + name + ", " + messages.getMessage()  
    return retMessage; 
  } 
} 

When we define this class, we create it as a subclass of the NSObject class. If a Swift class will be accessed from the Objective-C code, this class needs to be a subclass of the NSObject class. If we forget to do this, we will receive an error.

Now, let's look at how we will create an instance of the Objective-C Messages class in our Swift code. The code phrase let messages = Messages() creates the instance. As we can see, we create the instance of the Objective-C Messages class exactly as we would create an instance of any Swift class. We then access the getMessages() method like we would access a method of any Swift class.

As we can see from this code, Objective-C classes are both initiated and used as if they were written in Swift when we access them from a Swift type. This allows us to access our Objective-C and Swift types in a consistent way.

Now that we have created the Swift MessageBuilder class, we need a way to call the getPersonalizedMessage() method from the Objective-C ViewController class.

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

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