I have a swift project and i import a singleton, objective-c coded class in the project.
I tried to import the productname_swift.h file but no luck.
How can i access swift class in that singleton class?
Project made in Swift : To use Swift class in Objective C
To use Swift class in Objective C , follow given steps :
User.h
#import <Foundation/Foundation.h>
@interface User : NSObject
+(id) sharedUser ;
@end
User.m
#import "User.h"
#import "SwiftInObjectiveC-swift.h"
@implementation User
//Singleton of User
+(id)sharedUser{
static User *sharedUser = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedUser = [[self alloc] init];
//Class Method of ViewController.swift
[ViewController mySwiftClassFunction];
//Instance Method of ViewController.swift
ViewController *vc = [[ViewController alloc] init];
[vc mySwiftFunction];
});
return sharedUser;
}
-(void) myObjcectivecMethod {
ViewController *vc = [[ViewController alloc] init];
[vc mySwiftFunction];
}
Add @objc
in your .swift class in front of Class name.
import UIKit
@objc class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mySwiftFunction() {
print("Swift Function")
}
class func mySwiftClassFunction (){
print("Swift Class Function")
}
}
Go to Build Settings.
Set Product Module Name : ProjectName
Follow Apple link for Mix and Match for detailed information.
It is very simple use Swift classes in Objective-C. Just follow steps given below
Go to build settings type Swift Compiler and you will see Your
ProjectName-Swift.h
in Swift Compiler- General like below
Import you desired swift classes build and run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With