Junior — Middle
How is Swift code integrated into an Objective-C project?
sobes.tech AI
Answer from AI
Integration of Swift code into an Objective-C project is done using the so-called "Bridging Header" and the automatically generated file ProjectName-Swift.h.
Main steps:
-
In your Objective-C project, add a Swift file. Xcode will suggest creating a Bridging Header — it is needed for reverse integration of Objective-C into Swift, but for calling Swift from Objective-C, it is not mandatory.
-
To call Swift from Objective-C, use the automatically generated header file
ProjectName-Swift.h. You do not need to create it manually; Xcode generates it. -
In your Objective-C files, import this header:
#import "ProjectName-Swift.h"
- Now you can use public Swift classes and methods in Objective-C.
Important:
- Swift classes should be declared with the
@objcmodifier or inherit from NSObject to be visible in Objective-C.
Example of a Swift class:
@objc class MySwiftClass: NSObject {
@objc func greet() -> String {
return "Hello from Swift!"
}
}
In Objective-C:
MySwiftClass *obj = [[MySwiftClass alloc] init];
NSLog(@"%@", [obj greet]);