Swift code in Objective-C

Xcode allows to write you with a Swift and use it in your existing project which could be in Objective-C.

Consider the below UserObject Swift Written Class.
UserObject Class in Swift

import Foundation


class UserObject:NSObject {
    var userId:String?
    
    func printName(nameValue:String) -> Void {
        print("Name = \(nameValue)")
    }
    
   func printAnotherName(nameValue:String) -> Void {
        print("Name = \(nameValue)")
    }

}

ViewController in Objective-C

Now what if you want this newly written UserObject Swift Class to use in your existing Objective-C Class.


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UserObject *userObject = [[UserObject alloc] init];
    userObject.userId = @"1";
    [userObject printNameWithNameValue:@"John"];
    [userObject printNameSecond:@"Ray"];
}


@end



This will not work straight forward even though its in the same target. Below is the list of items that we need consider.


1) For Compiler to know which methods are to be available to Objective-C code, we need to use either @objc or @objcmembers attribute in Swift code.


2) When we create a Swift UserObject Class, Xcode will ask for bridging header file. This will be for both Objective-C and Swift code. But what we need to check currently is "Objective-C Generated Interface Header Name" in BuildSettings of the target.

ex: If the Product Module Name is "App1"  , the value of "Objective-C Generated Interface Header Name" will be "App1-Swift.h"

{PRODUCT_MODULE_NAME}-Swift.h

This will be auto-generated by Xcode, we don't have to create it.But it will ask you when you create a new Swift file in your Target.



The Code in Swift which is accessible to Objective-C code, will be converted to Objective-C code and will be available in this header file.

The final Swift Code will be like this.


@objcMembers
class UserObject:NSObject {
    var userId:String?
    
    func printName(nameValue:String) -> Void {
        print("Name = \(nameValue)")
    }
    
    @objc(printNameSecond:)func printAnotherName(nameValue:String) -> Void {
        print("Name = \(nameValue)")
    }

}


The same code can be used in your Objective-C UIViewController as listed below.

Note: The name of the second method is changed to printNameSecond: for Objective-C.


#import "ViewController.h"
#import "ObjectiveCApp-Swift.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   UserObject *userObject = [[UserObject allocinit];
    userObject.userId = @"1";
    [userObject printNameWithNameValue:@"John"];
    [userObject printNameSecond:@"Ray"];
}


@end

Comments

Popular posts from this blog

hitTest on iOS to identify the view being hit

CMTimeMakeWithSeconds explained

How to set Custom Section Header in UITableView for ios sdk version greater than 6