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.
Adding multiple Swift files to an Objective-C project.
Let's say you want to add Class1.swift , Class2.swift , and Class3.swift file to the SwiftToObjC project
@class Class1;
@class Class1;
@class Class2;
@class Class3;
5. In the target SwiftToObjC, under Build Settings , Swift-Compiler General you should see these two settings:
Objective-C Bridging Header -> SwiftToObjC-Bridging-Header.h
Objective-C Generated Interface Header Name -> SwiftToObjC-Swift.h
6. In the target SwiftToObjC, under Build Settings , Define Module is set to YES.
#import "SwiftToObjC-Bridging-Header.h"
@objc public class Class1: UITableViewController
Note that: UITableViewController is only an example for demonstration purpose.
That's all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.