How to Seamlessly Mix Swift and Objective‑C in a Single iOS Project
This guide walks you through configuring Xcode and writing code so that Swift can call Objective‑C and vice‑versa, covering bridging headers, generated Swift headers, and integrating a Swift framework into an Objective‑C host app.
Mixing Swift and Objective‑C in the Same Project
In Swift iOS development you often need to combine Swift and Objective‑C code. This article explains the two directions—Swift calling Objective‑C and Objective‑C calling Swift—along with the required Xcode configuration and code examples.
Swift accesses Objective‑C
Use a bridging header (ProductName-Bridging-Header.h) to import the Objective‑C class you want to expose, then instantiate and use that class directly in Swift.
Example steps: create an empty project, add a Swift class, let Xcode generate the bridging header, import the Objective‑C header, and write Swift code such as:
import UIKit
class SwiftClass01: NSObject {
var con: ViewController?
override init() {
super.init()
self.con = ViewController()
}
}Objective‑C accesses Swift
In Build Settings search for “Swift Compiler” and ensure the generated header (ProductName-Swift.h) is available. Import this header in the Objective‑C file and call Swift methods that are marked @objc and public.
Key points:
Methods that Objective‑C should call must be annotated with @objc.
Only public methods appear in the generated header.
The generated header automatically registers all Swift classes with an @interface.
Mixing a Swift Framework with an Objective‑C Host App
Create a Swift framework project (e.g., QiSwiftSdk.xcodeproj) and add it to the host app. In the host’s Build Phases set the framework as a target dependency.
In the host’s Objective‑C code, import the framework’s generated Swift header and call Swift classes that are declared open and whose methods are @objc public.
Important notes:
Expose Swift classes with the open keyword.
Mark callable methods with @objc public.
The framework’s own header (QiSwiftSdk.h) does not need additional modifications.
The framework can also contain its own bridging header for internal mixing.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
360 Zhihui Cloud Developer
360 Zhihui Cloud is an enterprise open service platform that aims to "aggregate data value and empower an intelligent future," leveraging 360's extensive product and technology resources to deliver platform services to customers.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
