Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 38 ยท Runtime and Interoperability

Interoperability with C, C++ and Swift

Mix Objective-C with C and C++ (Objective-C++), call Objective-C from Swift and back with bridging headers and NS_SWIFT_NAME, annotate nullability, and map types across the boundary.

Objective-C is a strict superset of C, so every C library is available as is. It also plays well with C++ through Objective-C++, and it interoperates closely with Swift, which means you can add Swift to an Objective-C app or keep an Objective-C core that Swift code calls. Knowing the rules of each border saves hours of confusing compiler errors.

Objective-C and C

Any valid C is valid Objective-C. You can call qsort, memcpy, POSIX sockets, and C frameworks such as Core Foundation, Core Graphics and libdispatch directly. You may mix C functions and Objective-C methods in the same file.

OBJECTIVEC
#include <math.h>
#include <string.h>

static double hypotenuse(double a, double b) { return sqrt(a * a + b * b); }   // plain C

@implementation Triangle
- (double)diagonal { return hypotenuse(self.base, self.height); }
@end

Things to remember:

  • C strings and NSString are different. Convert with [NSString stringWithUTF8String:cstr] and [str UTF8String]. The pointer from UTF8String is only valid while the string lives (and the current autorelease pool).
  • ARC does not manage C memory. malloc still needs free.
  • Objects cannot be members of C structs under ARC (unless the struct is only used with __unsafe_unretained pointers). Use a class instead, or store the object in an NSValue/NSArray.
  • Core Foundation types need toll-free bridging casts. See ARC for __bridge, __bridge_transfer and __bridge_retained.

Objective-C++

Rename a file from .m to .mm and the compiler treats it as Objective-C++: C++ and Objective-C in the same file. That lets an Objective-C class wrap a C++ library:

OBJECTIVEC
// Matrix.mm
#include <vector>
#include <algorithm>

@implementation Matrix {
    std::vector<double> _data;          // a C++ member inside an Objective-C ivar block
}
- (instancetype)initWithValues:(NSArray<NSNumber *> *)values {
    if ((self = [super init])) {
        for (NSNumber *n in values) _data.push_back(n.doubleValue);
    }
    return self;
}
- (double)maximum {
    return _data.empty() ? 0 : *std::max_element(_data.begin(), _data.end());
}
@end

Rules of the road:

  • Keep C++ types out of your public header, so that pure Objective-C files can import it without becoming .mm. Put C++ members in the implementation block or a class extension.
  • C++ exceptions and Objective-C exceptions are different mechanisms. Do not let one propagate across the other boundary.
  • Objective-C++ cannot make an Objective-C class inherit from a C++ class, or vice versa.
  • C++ objects with constructors and destructors work as ivars: ARC calls them when the Objective-C object is created and destroyed.

Annotations that help Swift (and you)

Objective-C is loosely typed about nil and about collection contents. Annotations tell the compiler (and Swift) more:

OBJECTIVEC
NS_ASSUME_NONNULL_BEGIN

@interface Contact : NSObject
@property (nonatomic, copy) NSString *name;                    // non-null
@property (nonatomic, copy, nullable) NSString *nickname;      // may be nil
@property (nonatomic, copy) NSArray<NSString *> *emails;       // typed collection
- (nullable instancetype)initWithName:(NSString *)name NS_DESIGNATED_INITIALIZER;
- (void)callWithCompletion:(void (^)(BOOL success))completion;
@end

NS_ASSUME_NONNULL_END

Inside NS_ASSUME_NONNULL_BEGIN/END, every pointer is non-null unless marked nullable. In Swift, nonnull becomes String, nullable becomes String?, and an unannotated pointer becomes an implicitly unwrapped String!, which is why unannotated headers are dangerous.

More helpful macros:

Macro Effect
NS_SWIFT_NAME(...) Choose the Swift name
NS_ENUM / NS_OPTIONS Enums that import as real Swift enums/option sets
NS_REFINED_FOR_SWIFT Hide the method and expose it with a __ prefix for a Swift wrapper
NS_UNAVAILABLE Mark an initializer as not callable
__kindof A subclass type, such as NSArray<__kindof UIView *> *
Lightweight generics NSArray<NSString *> import as [String]

Using Objective-C from Swift

Add a bridging header (MyApp-Bridging-Header.h) and #import your Objective-C headers in it. In a framework target, use the umbrella header instead. Swift then sees your classes automatically:

OBJECTIVEC
// Objective-C
@interface Calculator : NSObject
- (NSInteger)addFirst:(NSInteger)a second:(NSInteger)b;
- (void)loadItemsWithCompletion:(void (^)(NSArray<NSString *> * _Nullable items, NSError * _Nullable error))completion;
@end
Swift
// Swift sees:
let calc = Calculator()
let total = calc.add(first: 2, second: 3)            // labels derived from the selector
calc.loadItems { items, error in /* ... */ }         // blocks become closures
// Methods ending in an NSError** parameter become `throws`

Swift renames selectors (addFirst:second: becomes add(first:second:)), imports NSError ** methods as throws, BOOL as Bool, NSArray<NSString *> as [String], and blocks as closures. Mark a block's escaping behavior with NS_NOESCAPE when it is called before the method returns.

Using Swift from Objective-C

Xcode generates a header YourModule-Swift.h; #import it in your .m files. Only Swift declarations that Objective-C can express are exposed: classes that inherit from NSObject (or are marked @objc), and members marked @objc (or @objcMembers).

Swift
// Swift
@objc public class Greeter: NSObject {
    @objc public var name: String
    @objc public init(name: String) { self.name = name }
    @objc public func greet() -> String { "Hello, \(name)" }
}
OBJECTIVEC
// Objective-C
#import "MyApp-Swift.h"

Greeter *g = [[Greeter alloc] initWithName:@"Ada"];
NSLog(@"%@", [g greet]);

Swift-only features (generics, structs, enums with associated values, tuples, async without @objc wrappers) do not cross the border. Design the shared API around classes, protocols, NSObject-friendly types and completion handlers.

flowchart LR
  OC["Objective-C code (.m)"] -- "#import Module-Swift.h" --> SW["Swift code (@objc, NSObject)"]
  SW -- "bridging header" --> OC
  OC --- C["C / C++ (.mm)"]

Each arrow shows the file that makes one side visible to the other.

Stable boundaries: a C-style API model

The safest cross-language interface is a plain C ABI: function pointers and opaque handles. That is why many libraries expose a C API that Objective-C, Swift and C++ can all wrap. The stand-in below shows an opaque handle with create/use/destroy functions, which is how most C libraries hide their internals from callers.

C Stand-in: an opaque-handle C API (the stable boundary)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

An Objective-C wrapper class does exactly this: it creates the C handle in init and frees it in dealloc, so ARC manages the lifetime of the foreign resource.

Converting types at the border

C strings, byte buffers and numbers need explicit conversions:

C Stand-in: converting at the boundary - C string, bytes and numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What file extension makes the compiler treat a source file as Objective-C++?

    .mm enables C++ in addition to Objective-C.
  2. 2. How does Swift see an Objective-C method with a trailing NSError ** parameter?

    Swift imports the error-out-parameter convention as a throwing function.
  3. 3. What does NS_ASSUME_NONNULL_BEGIN do?

    It sets the default nullability so only the exceptions need annotating.
  4. 4. Which Swift declaration can Objective-C see?

    Only Objective-C representable constructs are exposed in the generated header.

Summary

  • Objective-C is a superset of C; manage C memory yourself and convert strings and numbers explicitly.
  • .mm files mix in C++; keep C++ types out of public headers.
  • Nullability annotations, NS_SWIFT_NAME and NS_ENUM make Objective-C APIs pleasant in Swift.
  • Swift reaches Objective-C through a bridging header; Objective-C sees Swift through the generated -Swift.h header and @objc.

Next: Project: Bank Accounts and JSON Models