Bridging Header: Mixing Objective-C and Swift

A bridging header is a translation list for Xcode, letting your new Swift code call old Objective-C code. It's essential when migrating a legacy codebase or using an Objective-C library. The footgun: it only exposes Objective-C to Swift, not vice-versa.
WHY IT EXISTS: Apple introduced Swift as a modern replacement for Objective-C but knew developers had massive, existing codebases. A bridging header enables gradual adoption, allowing new features in Swift to coexist and interact with battle-tested Objective-C code without a full rewrite.
THE MENTAL MODEL: Think of the bridging header as a special manifest for the Swift compiler. You are providing a single list of all the 'old world' Objective-C files you want the 'new world' of Swift to know about. It's a one-way bridge that brings Objective-C declarations into the Swift environment.
HOW IT WORKS: When you add an Objective-C file to a predominantly Swift project, Xcode offers to create a file named YourProject-Bridging-Header.h. In this file, you add standard Objective-C import statements, like #import "MyLegacyView.h". Once a header is listed here, all of its public classes, methods, and types become automatically available to every Swift file in that target. No import statements are needed in your Swift code.
WHEN TO USE IT: Use a bridging header whenever you need to call Objective-C code from Swift within the same application target. This is common when incrementally migrating an old app to Swift or when using a third-party library distributed as Objective-C source files.
WHEN NOT TO USE IT: You do not need a bridging header for a pure Swift project or for using Swift code from Objective-C. That reverse scenario is handled differently: Xcode automatically generates a header named YourProject-Swift.h. You import this special header into your Objective-C .m files to access your public Swift classes.
ONE CANONICAL EXAMPLE: Suppose you have an existing Objective-C class AnalyticsTracker.h. To use it from a new CheckoutView.swift, you first add the line #import "AnalyticsTracker.h" to your project's bridging header. Then, inside CheckoutView.swift, you can instantiate and use it directly as if it were a native Swift type: let tracker = AnalyticsTracker.shared(); tracker.logEvent("checkout_started"). The compiler handles the translation.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.