Call Swift class from Objective-C

Apply Objective-C class for Swift code

Basically, we cannot use swift class from Objective-C

In this entry, we use Swift Framework from Objective-C App.

Swift code

import Foundation

public class Region : NSObject {   
    public class func getRegion() -> String {
        return NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String
    }
    
    public class func isSupported() -> Bool {  // only for Japan
        return self.getRegion() == "JP"
    }
}

Objective-C class

Swift class should be extended NSObject to use swift from Objective-C
If you skip extend class, the class becomes swift class.
If you want to use class which is not NSObject class, you need to add @objc annotation before class

@objc class Region {
}

And you want to change the name for Objective-C?

@objc(RegionObjc) class Region {
}

Header

After build, you can see Swift header from your framework.

SWIFT_CLASS("_TtC13SDKTechSample6Region")
@interface Region : NSObject
+ (NSString * __nonnull)getRegion;
+ (BOOL)isSupported;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end

XCode Build Setting

To use swift class, we need to change Build Setting

Screen Shot 2015-12-07 at 5.37.44 PM

Objective-C code

#import "ViewController.h"
#import <SDKTechSample/SDKTechSample-Swift.h>

@interface ViewController ()
@property (nonatomic) UIImageView *imageView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@", [Region getRegion]);
}
@end