skip to content

Objective-C and C Bridging

Swift calls Objective-C, C and C++ through bridging headers and modules, and exposes code back with @objc. Interviewers ask how nullability maps and why @objc dynamic matters.

on this pageshow

explore

questions

6

In a mixed Swift and Objective-C app, why can't an Objective-C file call a new Swift method, and what makes it visible?

level: middleimportance: must knowfreq 62%

answer

  1. two headers, two directions
  2. what the compiler prints for Objective-C
  3. Swift 4 narrowed the inference
  4. representable parameter types only

basics

~20 s

Objective-C sees Swift only through the compiler-generated ModuleName-Swift.h header, which prints only declarations exposed with @objc. Since Swift 4, sitting in an NSObject subclass no longer exposes a method by itself, so a new method needs @objc and Objective-C-representable types.

solid answer

~40 s

The two directions use two headers. Swift sees Objective-C through the bridging header (or a module); Objective-C sees Swift through the header the compiler generates, `ModuleName-Swift.h`, which an `.m` file imports. That header prints only `@objc` declarations. Since Swift 4 (SE-0160), sitting inside an `NSObject` subclass no longer infers `@objc`: it is inferred for overrides of `@objc` members, for witnesses of `@objc` protocol requirements, and for members marked `@IBAction`, `@IBOutlet`, `@NSManaged` and a few similar attributes. So you write `@objc` on the member, on an extension, or `@objcMembers` on the class, and every parameter and result must be representable in Objective-C. When the module imports a bridging header, as an app target does, the generated header also lists `internal` `@objc` members; otherwise it lists only `public` and `open` ones.

code

swift · 16 lines
swift
import Foundation

@objc protocol PhotoExportDelegate {
  func exporterDidFinish(_ exporter: PhotoExporter)
}

class PhotoExporter: NSObject {
  @objc var quality: Double = 0.8
  @objc func start(photoID: String) {}   // printed in the generated header
  func cancel() {}                       // Swift-only since Swift 4
}

final class Uploader: NSObject, PhotoExportDelegate {
  // @objc inferred: it satisfies an @objc protocol requirement
  func exporterDidFinish(_ exporter: PhotoExporter) {}
}

go deeper

for a junior

Remember the two directions: the bridging header brings Objective-C into Swift, the generated ModuleName-Swift.h brings Swift into Objective-C, and only @objc members appear there.

for a middle

Explain the SE-0160 inference rules: overrides of @objc members, @objc protocol witnesses and Interface Builder or Core Data attributes infer @objc; everything else needs it written.

for a senior

Show how you diagnose a missing selector: read the generated header, check access level against the target type, and add a representable @objc wrapper when the signature uses Swift-only types.

for a principal

Weigh exposure cost: each @objc entry point adds a thunk and metadata, so prefer narrow @objc over @objcMembers and shrink the exposed surface as Objective-C callers disappear.

## Two headers, two directions A mixed app crosses the language boundary in two directions, and each direction has its own header: - **Objective-C into Swift**: the **bridging header** (in an app target) or a Clang module lists the Objective-C headers Swift should import. Swift then sees those classes and functions as Swift declarations. - **Swift into Objective-C**: the compiler **generates** a header, `ModuleName-Swift.h`, that translates the module's Objective-C-visible Swift declarations into `@interface` and `@protocol` declarations. An `.m` file imports it like any other header. A method that is missing from the generated header does not exist as far as the Objective-C compiler is concerned: a direct call is rejected because no visible interface declares the selector, and a message sent dynamically fails at run time as an unrecognized selector. ## What the generated header contains The header prints **only declarations that are `@objc`**, whether written or inferred. Access level filters it a second time: | Module | Members printed | |---|---| | Imports a bridging header (the usual app target) | `@objc` members at `internal`, `public` or `open` | | No bridging header (a framework) | only `public` and `open` `@objc` members | Swift types are translated: a non-optional `String` becomes `NSString * _Nonnull`, and a method `start(photoID:)` becomes the selector `startWithPhotoID:`. ## When Swift infers `@objc`, and when it stopped Swift 3 exposed almost every member of an `NSObject` subclass whose types Objective-C could represent. **SE-0160, implemented in Swift 4**, cut that back to the cases where an Objective-C entry point is required for the model to hold together. `@objc` is still inferred when: 1. the declaration **overrides** an `@objc` declaration; 2. it **satisfies a requirement of an `@objc` protocol**; 3. it carries `@IBAction`, `@IBSegueAction`, `@IBOutlet`, `@IBDesignable`, `@IBInspectable`, `@NSManaged` or `@GKInspectable`. The class itself is implicitly `@objc` when it inherits from a class defined in Objective-C, but its members are not. A plain method added to a view model that subclasses `NSObject` is therefore Swift-only until you mark it. ## Ways to expose a member - `@objc` on the member: the narrow, preferred choice. `@objc(name)` also sets the selector, which you need when two Swift overloads would map to one selector. - `@objc extension`: every member of the extension is exposed, and the compiler errors on any member that cannot be. - `@objcMembers` on the class: re-enables inference for the class, its extensions and its subclasses. The Swift book recommends `@objc` for most code, because every entry point costs a thunk and metadata. - `@nonobjc` opts a single member back out. ## Representability `@objc` only works when every type in the signature has an Objective-C form: classes that are `@objc`, bridged value types such as `String`, and `Array` or `Dictionary` of representable elements, integer and floating-point scalars, `@objc` protocols, and enums declared `@objc` with an integer raw type. A Swift struct parameter, a tuple result, an enum with associated values or a generic signature is rejected at compile time with an error such as "instance method cannot be marked '@objc' because the type of the parameter cannot be represented in Objective-C". ## `#selector`, strings and protocol extensions - `#selector(PhotoExporter.cancel)` does not compile when `cancel()` is not `@objc`: Swift reports "argument of '#selector' refers to instance method 'cancel()' that is not exposed to Objective-C". This is the Swift-side signal of the same gap. - Messages sent with a selector built from a string, such as `perform(NSSelectorFromString("cancel"))`, compile anyway and fail only at run time with an unrecognized selector, so search the Objective-C side for string selectors before narrowing exposure. - A default implementation in an extension of an `@objc` protocol gets no Objective-C entry point either; an Objective-C caller asking `respondsToSelector:` gets `NO`. ## Diagnosing the missing method 1. Open the generated header (Xcode can jump to it) and search for the selector. 2. If it is absent, check whether the member is `@objc`, and whether its access level clears the table above. 3. If the compiler refuses `@objc`, change the signature: pass a class or a bridged type, or add an `@objc` wrapper method that takes representable values and calls the Swift-only one. 4. In Objective-C headers of the same module, forward-declare the Swift class with `@class` and import the generated header only in the `.m` file: the generated header cannot be included in the module's own headers without creating a cycle.

  • Two Swift initializers init(_ int: Int) and init(_ double: Double) in an NSObject subclass are both marked @objc; what happens?
    Both map to the selector `init:`, so Swift rejects the second with "initializer 'init(_:)' with Objective-C selector 'init:' conflicts with previous declaration with the same Objective-C selector". Give each an explicit name, such as `@objc(initWithInteger:)` and `@objc(initWithDouble:)`, or mark one `@nonobjc` if Objective-C never calls it.
  • Why does an Objective-C header in the same app target struggle to use a Swift class?
    The generated header is produced while the Swift half of the module is compiled, so it cannot be imported into that module's own headers without a cycle. The usual pattern is a `@class PhotoExporter;` forward declaration in the `.h` file and `#import "ModuleName-Swift.h"` in the `.m` file, where the full interface is needed.

The generated header is a published phone directory for Objective-C callers: a Swift method that never asked to be listed with @objc exists, but nobody on the Objective-C side can look up its number.

  • Subclassing NSObject exposes every Swift method to Objective-C automatically.
  • The bridging header is what lets Objective-C code see Swift code.
  • @objc can be added to any method, whatever its parameter types.
  • Marking a method dynamic is enough to expose it to Objective-C.
  • @objcMembers is a free default worth putting on every class.
open as a page

When Swift imports an Objective-C header, how do nullability annotations, lightweight generics and NS_ENUM declarations decide the Swift types you get?

level: middleimportance: must knowfreq 58%

basics

~20 s

Unannotated Objective-C pointers import as implicitly unwrapped optionals, nullable as optionals, nonnull as plain types; NSArray<NSString *> becomes [String] while a bare NSArray becomes [Any]; NS_ENUM becomes a non-frozen Swift enum and NS_OPTIONS an OptionSet struct.

open as a page

A Swift NSObject subclass's property is observed with KVO, yet assignments made from Swift never notify; why does it need @objc dynamic?

level: seniorimportance: should knowfreq 45%

basics

~20 s

KVO notifies by intercepting the setter through the Objective-C runtime. @objc only adds an Objective-C entry point; Swift callers still reach the setter through Swift's own dispatch and bypass the interception. dynamic forces every access through Objective-C messaging, so the observer fires.

open as a page

A Swift call into a C image-decoding library returns Unmanaged<CFData>?; what does that tell you, and how do you choose takeRetainedValue or takeUnretainedValue?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Unmanaged means Swift could not tell whether the C function returns an owned (+1) or borrowed (+0) Core Foundation object. Use takeRetainedValue for Create or Copy functions, which hand you ownership, and takeUnretainedValue for Get functions, which do not.

open as a page

For an app with a decade of Objective-C screens, a C image decoder and Objective-C++ wrappers around a C++ geometry library, how would you plan the Swift migration of its interop boundaries?

level: principalimportance: should knowfreq 30%

basics

~20 s

Annotate the Objective-C and C headers first, write new leaf code as @objc Swift, port classes Objective-C still subclasses with @objc @implementation (Swift 6.1), and replace Objective-C++ wrappers with C++ interoperability only behind one Swift module that keeps the mode contained.

open as a page

In Swift, what changes when a target enables C++ interoperability mode to call a C++ geometry library, and what must modules importing it do?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

With -cxx-interoperability-mode=default, Swift imports C++ headers directly: copyable C++ classes become Swift value types, std::string and std::vector become usable, and annotated reference-counted classes become ARC-managed references. Modules that see those C++ types through a public import must enable the mode too.

open as a page