Skip to the workspace
Pebellslearn by building
Choosing a Language  ›  Capstone Project

Interoperability with Swift

Interoperability with Swift 12 minSwift sees Objective-C code imported through a bridging header, and Objective-C sees Swift classes marked @objc through a generated header.

ios / Interoperability with Swift

Explore each scene at your own pace.

01 · The rule

The rule

Interoperability with Swift

TrailLog's photo filter was written in Objective-C years ago and works perfectly. Nobody wants to rewrite it just to call it from new Swift screens. Apple built the two languages to live in the same app, so you can mix them file by file.

The rule

Objective-C enters Swift through the bridging header; Swift leaves through @objc.

There are two directions, each with its own doorway.

Objective-C → Swift. Add a bridging header, a file usually named TrailLog-Bridging-Header.h, and import the Objective-C headers you want Swift to see:

// TrailLog-Bridging-Header.h
#import "PhotoFilter.h"

Now any Swift file in the app can use PhotoFilter as if it were Swift. Xcode translates the names: [filter applyToImage:photo] becomes filter.apply(to: photo).

Swift → Objective-C. Xcode generates a header named TrailLog-Swift.h. Objective-C files #import it. Only Swift declarations that Objective-C can understand appear there:

@objc class HikeExporter: NSObject {
    @objc func exportAll() { /* ... */ }
}

The class inherits from NSObject and is marked @objc, so Objective-C can see it. A Swift struct, or an enum with associated values, has no Objective-C equivalent and stays invisible.

One more translation matters: nullability. Objective-C headers can say whether a pointer may be nil:

- (nullable UIImage *)thumbnailForHike:(nonnull Hike *)hike;

Swift reads nullable as an optional (UIImage?) and nonnull as a plain value (Hike). With no annotation at all, Swift has to guess and imports an implicitly unwrapped optional (UIImage!), which crashes if it turns out to be nil.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.