Swift Interoperability
Most Apple-platform apps today are written in Swift, but huge amounts of Objective-C remain, and the two languages are designed to live in the same project. This lesson explains how each side sees the other and how to write Objective-C that feels natural in Swift. The Swift and Xcode parts can't run here; the Objective-C examples show the annotations you'd use.
How the bridge works
Objective-C → Swift Swift → Objective-C
┌───────────────────────────┐ ┌─────────────────────────────────┐
│ MyApp-Bridging-Header.h │ │ MyApp-Swift.h (generated) │
│ #import "Account.h" │ │ declares @objc Swift classes │
│ #import "Vault.h" │ │ #import "MyApp-Swift.h" in .m │
└───────────────────────────┘ └─────────────────────────────────┘- Objective-C to Swift: in an app target, list the headers in the bridging header. In a framework, the umbrella header / module map does the same. Swift then sees those classes as if they were Swift types.
- Swift to Objective-C: Xcode generates a header named
<Module>-Swift.h. Swift classes that inherit fromNSObjectand members marked@objcappear in it.
What Swift sees
Given this header, Swift's importer applies a set of renaming and typing rules:
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, TADAccountKind) {
TADAccountKindChecking,
TADAccountKindSavings,
};
@interface TADAccount : NSObject
@property (nonatomic, copy) NSString *owner;
@property (nonatomic, copy, nullable) NSString *nickname;
@property (nonatomic, readonly) TADAccountKind kind;
@property (nonatomic, copy) NSArray<NSString *> *tags;
- (instancetype)initWithOwner:(NSString *)owner kind:(TADAccountKind)kind;
- (BOOL)withdrawAmount:(double)amount error:(NSError **)error;
- (void)fetchStatementWithCompletion:(void (^)(NSString * _Nullable text, NSError * _Nullable error))completion;
+ (instancetype)accountWithOwner:(NSString *)owner;
@end
NS_ASSUME_NONNULL_END// The same API, as imported into Swift
let acc = TADAccount(owner: "Ines", kind: .savings) // init + enum prefix stripped
acc.nickname = nil // nullable -> String?
let tags: [String] = acc.tags // NSArray<NSString *> -> [String]
do {
try acc.withdrawAmount(50) // BOOL + NSError** -> throws
} catch {
print(error.localizedDescription)
}
let text = try await acc.fetchStatement() // completion handler -> async
let other = TADAccount(owner: "Leo") // factory method -> initializer| Objective-C | Swift |
|---|---|
NSString *, NSArray<T> *, NSDictionary<K,V> * |
String, [T], [K: V] (bridged value types) |
NSInteger, BOOL, double |
Int, Bool, Double |
nullable / nonnull / unannotated |
T? / T / T! |
initWithOwner:kind: |
init(owner:kind:) |
+accountWithOwner: (factory) |
init(owner:) |
- (BOOL)doX:(…)error:(NSError **) |
func doX(…) throws |
| completion-handler methods | also available as async functions |
NS_ENUM / NS_OPTIONS |
Swift enum / OptionSet |
id |
Any |
| blocks | closures |
The patterns Swift converts
Swift's automatic throws and async translations only work if the Objective-C side follows the conventions exactly: a BOOL (or nullable object) result with a final NSError ** parameter, and a completion block as the last parameter whose arguments are the result and an optional error. Here is a class following both, used from Objective-C:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Profile : NSObject
// Swift: func rename(to name: String) throws
- (BOOL)renameTo:(NSString *)name error:(NSError **)error;
// Swift: func loadBio() async throws -> String
- (void)loadBioWithCompletion:(void (^)(NSString * _Nullable bio, NSError * _Nullable error))completion;
@property (nonatomic, copy, readonly) NSString *name;
@end
NS_ASSUME_NONNULL_END
@implementation Profile
- (BOOL)renameTo:(NSString *)name error:(NSError **)error {
if (name.length < 2) {
if (error) {
*error = [NSError errorWithDomain:@"Profile" code:1
userInfo:@{NSLocalizedDescriptionKey: @"Name too short."}];
}
return NO;
}
_name = [name copy];
return YES;
}
- (void)loadBioWithCompletion:(void (^)(NSString *, NSError *))completion {
if (self.name) {
completion([NSString stringWithFormat:@"%@ writes Objective-C.", self.name], nil);
} else {
completion(nil, [NSError errorWithDomain:@"Profile" code:2
userInfo:@{NSLocalizedDescriptionKey: @"No profile yet."}]);
}
}
@end
int main(void) {
@autoreleasepool {
Profile *p = [Profile new];
void (^show)(NSString *, NSError *) = ^(NSString *bio, NSError *error) {
NSLog(@"%@", bio ?: [@"error: " stringByAppendingString:error.localizedDescription]);
};
[p loadBioWithCompletion:show];
NSError *error = nil;
if (![p renameTo:@"K" error:&error]) {
NSLog(@"rename failed: %@", error.localizedDescription);
}
[p renameTo:@"Kai" error:&error];
[p loadBioWithCompletion:show];
}
return 0;
}error: No profile yet.
rename failed: Name too short.
Kai writes Objective-C.
Designing Objective-C for Swift
The rules above work best when your header is precise. A runnable reminder of the most important annotations, written the way you'd ship them:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, TemperatureUnit) {
TemperatureUnitCelsius,
TemperatureUnitFahrenheit,
};
@interface Thermometer : NSObject
@property (nonatomic, readonly) double celsius;
@property (nonatomic, copy, nullable) NSString *location;
- (instancetype)initWithCelsius:(double)celsius NS_DESIGNATED_INITIALIZER;
- (instancetype)init __attribute__((unavailable("use initWithCelsius:")));
- (double)readingInUnit:(TemperatureUnit)unit;
- (NSArray<NSNumber *> *)forecastForDays:(NSInteger)days;
@end
NS_ASSUME_NONNULL_END
@implementation Thermometer
- (instancetype)initWithCelsius:(double)celsius {
self = [super init];
if (self) { _celsius = celsius; }
return self;
}
- (double)readingInUnit:(TemperatureUnit)unit {
switch (unit) {
case TemperatureUnitCelsius: return self.celsius;
case TemperatureUnitFahrenheit: return self.celsius * 9 / 5 + 32;
}
return self.celsius;
}
- (NSArray<NSNumber *> *)forecastForDays:(NSInteger)days {
NSMutableArray<NSNumber *> *out = [NSMutableArray array];
for (NSInteger d = 1; d <= days; d++) {
[out addObject:@(self.celsius + d * 0.5)];
}
return [out copy];
}
@end
int main(void) {
@autoreleasepool {
Thermometer *t = [[Thermometer alloc] initWithCelsius:20];
t.location = @"Lab";
NSLog(@"%@: %.1f C / %.1f F", t.location,
[t readingInUnit:TemperatureUnitCelsius], [t readingInUnit:TemperatureUnitFahrenheit]);
NSLog(@"forecast: %@", [[t forecastForDays:3] componentsJoinedByString:@", "]);
}
return 0;
}Lab: 20.0 C / 68.0 F
forecast: 20.5, 21, 21.5
In Swift this becomes Thermometer(celsius: 20), t.location: String?, t.reading(in: .fahrenheit) and t.forecast(forDays: 3) -> [NSNumber], while Thermometer() is unavailable.
Further annotations from Apple's SDK (available in Xcode):
| Annotation | Effect in Swift |
|---|---|
NS_SWIFT_NAME(newName(…)) |
choose the exact Swift name |
NS_REFINED_FOR_SWIFT |
hide the raw method (prefixed __) so a nicer Swift wrapper can replace it |
NS_SWIFT_UNAVAILABLE("…") |
hide a method from Swift entirely |
NS_SWIFT_NOTHROW |
keep an NSError ** method from becoming throws |
NS_TYPED_ENUM |
turn string constants into a Swift struct |
Swift code used from Objective-C
// Greeter.swift
import Foundation
@objc(TADGreeter) // the name Objective-C sees
class Greeter: NSObject { // must inherit from NSObject to be visible
@objc var name: String
@objc init(name: String) { self.name = name }
@objc func greeting(loud: Bool) -> String {
loud ? "HELLO, \(name.uppercased())!" : "Hello, \(name)."
}
func swiftOnly() -> (Int, Int) { (1, 2) } // tuples can't be expressed in ObjC
}// SomeController.m
#import "MyApp-Swift.h"
TADGreeter *g = [[TADGreeter alloc] initWithName:@"Ada"];
NSLog(@"%@", [g greetingWithLoud:YES]);Swift-only features (structs, enums with associated values, generics, tuples, async without @objc) don't cross the bridge. The common strategy is to keep the boundary in classes and protocols that both languages understand.
Migrating a codebase
- Annotate existing headers with nullability and generics first: it improves the Swift view immediately.
- Write new code in Swift; call old Objective-C through the bridging header.
- Move leaf classes (no dependents) to Swift one at a time, keeping their public API the same so callers don't change.
- Remove the Objective-C versions when nothing imports them any more.
Test yourself
Which file exposes Objective-C headers to Swift in an app target?
- Info.plist
- The bridging header
- MyApp-Swift.h
- main.m
How is - (BOOL)saveFile:(NSString *)path error:(NSError **)error; imported into Swift?
- func saveFile(_ path: String) -> Bool
- func saveFile(_ path: String) throws
- func saveFile(_ path: String, error: NSError)
- It isn't imported
What must a Swift class do to be usable from Objective-C?
- Be a struct
- Inherit from NSObject (and expose members with @objc)
- Use the open keyword
- Nothing