tezvyn:

Purpose and setup of an Objective-C bridging header

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

mixed-language project setup.

OUTLINE

the bridging header imports ObjC headers into Swift; Xcode auto-creates it or you add it manually and set the build setting.

RED FLAG

confusing it with the generated Swift-to-ObjC header.

WHAT THIS TESTS The interviewer wants to know if you can integrate legacy or third-party Objective-C code into a Swift target, a common reality in mature iOS codebases. It checks your grasp of how the two compilers see each other.

A GOOD ANSWER COVERS A bridging header is a plain Objective-C header file, conventionally named ProductName-Bridging-Header.h, in which you #import every Objective-C header whose declarations you want Swift to see. Xcode usually creates it automatically and prompts you the first time you add an Objective-C file to a Swift target, or you create it manually and point the Objective-C Bridging Header build setting at its path. Once set, the imported classes, methods, and macros appear in Swift with no per-file import, subject to normal Swift name translation.

COMMON WRONG ANSWERS Conflating the bridging header with the generated ProductName-Swift.h, which exposes Swift back to Objective-C and is created by the compiler, not by you. Another is claiming you need one bridging header per class, or that frameworks use a bridging header. Framework targets cannot use bridging headers; they expose Objective-C through an umbrella header and a module map instead.

LIKELY FOLLOW-UPS How does the reverse direction work? How do you expose Swift to Objective-C? Why can a framework not use a bridging header? How does Swift translate Objective-C naming conventions like NSError pointers?

ONE CONCRETE EXAMPLE You add a battle-tested LegacyImageCache written in Objective-C to a SwiftUI app. You add LegacyImageCache.h and .m to the app target. Xcode prompts to create the bridging header; you accept and write #import "LegacyImageCache.h" inside it. In Swift you immediately call LegacyImageCache.shared.image(forKey:) with full type information, while the rest of the app stays pure Swift.

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.