In Swift, what changes when a target enables C++ interoperability mode to call a C++ geometry library, and what must modules importing it do?
answer
- a compiler flag, off by default
- requires cplusplus in the module map
- value types versus shared references
- ownership annotations on returned pointers
- the mode spreads through public imports
basics
~20 sWith -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.
solid answer
~50 sC++ interoperability, shipped in Swift 5.9, is off by default; a target turns it on with `-cxx-interoperability-mode=default`, which tracks the target's language mode. The C++ headers sit in a Clang module whose module map says `requires cplusplus`. Swift then imports C++ structs and classes with copy constructors and destructors as **value types**: copies run the copy constructor, `const` methods are non-mutating and other methods `mutating`. `std::string` and `std::vector` work directly, and a vector iterates with `for`-`in`. A class annotated `SWIFT_SHARED_REFERENCE(retain, release)` imports as a **foreign reference type** that ARC retains and releases with those functions; returned pointers need `SWIFT_RETURNS_RETAINED` or `SWIFT_RETURNS_UNRETAINED`, or the compiler warns that it cannot infer ownership. Any module that sees the C++ module through a public import must enable the mode too, or the import fails because the module requires `cplusplus`.
code
swift · 19 lines// Geometry.hpp, exposed by a module map with `requires cplusplus`:
// struct Vec2 { double x = 0, y = 0; double length() const;
// void scale(double k) { x *= k; y *= k; } };
// class Polygon { public: std::vector<Vec2> points; std::string name; };
// class Mesh { ... } SWIFT_SHARED_REFERENCE(meshRetain, meshRelease);
// Mesh *makeMesh() SWIFT_RETURNS_RETAINED;
import Geometry
func describe() -> String {
var v = Vec2(x: 3, y: 4)
v.scale(2) // non-const method: mutating
var poly = Polygon()
poly.points.push_back(v)
poly.name = std.string("triangle")
var sumX = 0.0
for p in poly.points { sumX += p.x }
let mesh = makeMesh()! // foreign reference type, ARC-managed
return "\(String(poly.name)) \(sumX) \(mesh.vertexCount()) \(v.length())"
}go deeper
Recall that calling C++ from Swift needs the C++ interoperability mode and a module map for the C++ headers.
Explain the import rules: copyable classes as value types, const methods non-mutating, std::vector usable directly, shared references managed by ARC.
Diagnose the build and ownership failures: importers missing the mode, unannotated pointer returns, and C++ types leaking through public signatures.
Decide where the C++ boundary sits: one Swift module hiding C++ behind an internal import, or an Objective-C++ wrapper layer kept for stability.
## Turning the mode on Swift has always imported C and Objective-C. Importing **C++** needs the **C++ interoperability mode**, which shipped in Swift 5.9 and is off by default: - Pass `-cxx-interoperability-mode=default` to the Swift compiler. In Xcode that can go in the target's Swift compiler flags; Swift packages and CMake builds have equivalent settings. - `default` means the interop compatibility version follows the target's language mode, so a Swift 6 mode target gets the Swift 6 interop behaviour. A specific version such as `swift-5.9` can be pinned, and `upcoming-swift` opts into unreleased changes. - Expose the C++ headers as a **Clang module**: a `module.modulemap` naming the header, conventionally with `requires cplusplus`. Without the mode, importing that module fails with "module 'Geometry' requires feature 'cplusplus'". ## How C++ types arrive | C++ declaration | Swift sees | |---|---| | `struct Vec2 { double x, y; double length() const; void scale(double); }` | a struct `Vec2` with `init(x:y:)`, a non-mutating `length()` and a `mutating` `scale(_:)` | | A class with a copy constructor and destructor, such as `std::vector<Vec2>` or `std::string` | a **value type**: Swift copies call the copy constructor, destruction calls the destructor | | A class annotated `SWIFT_SHARED_REFERENCE(meshRetain, meshRelease)` | a **foreign reference type**: ARC calls those two functions | | A class annotated `SWIFT_IMMORTAL_REFERENCE` | a reference type that is never released | | A parameter `Vec2 &` / `const Vec2 &` | `inout Vec2` / a `Vec2` value | Practical consequences: - **`const` matters.** A non-`const` method imports as `mutating`, so calling `scale(_:)` on a `let` constant is a compile error. - **Standard-library types work.** `poly.points.push_back(v)` and `for p in poly.points` compile; `String(cxxString)` and `std.string("triangle")` convert between `String` and `std::string`. - **Unsafe projections are restricted.** A method that returns a pointer or iterator into an owned value (a projection) is imported as unsafe, because Swift's copies and lifetimes of the owning value do not match C++'s. ## Reference types and ownership C++ often hands out objects by pointer with its own reference counting. `SWIFT_SHARED_REFERENCE` tells Swift which functions retain and release, so a `Mesh` behaves like a class. A function returning `Mesh *` must also say whether the pointer is +1 or +0: 1. `SWIFT_RETURNS_RETAINED` for a fresh, owned object; 2. `SWIFT_RETURNS_UNRETAINED` for one someone else owns; 3. neither: Swift 6.4 warns "cannot infer ownership of foreign reference value returned by 'makeMesh()'", because it might insert a retain too many or too few. A `Mesh *` return without a nullability annotation also imports as an optional `Mesh?`, since the pointer may be null. ## What modules that import it must do The C++ mode is a property of each compilation, not only of the library: - When a Swift module re-exports C++ types, through a `public import` or public signatures that use them, every module that imports it must enable the mode as well, or the import fails because the C++ module requires `cplusplus`. - A library built with library evolution that keeps the C++ module behind an `internal import` and exposes only Swift types can let its importers build without the mode; in practice that thin Swift layer is the usual way to keep C++ from spreading. - C++ interoperability is still evolving between releases, so pinning a compatibility version and building the C++ module with the same toolchain avoids surprises. ## The other direction: C++ calling Swift The interop is bidirectional. With the mode enabled, the compiler can also generate a C++ header for a Swift module, `MyModule-Swift.h`, which C++ code includes to call public Swift functions and types through a `MyModule::` namespace. The header needs Clang, and C++20 is the recommended standard. The guide for this direction is marked as a living, work-in-progress design, so treat it as less settled than calling C++ from Swift. ## What it replaces Before Swift 5.9, a team calling C++ from Swift wrote **Objective-C++ wrapper classes**: an `.mm` file that owned the C++ object and exposed an Objective-C interface for Swift to import. The interop mode removes that layer for the API subset it imports well: value types, standard containers, annotated reference types. It does not remove the need to design the boundary: plain Objective-C `.m` files cannot call C++ at all, so wrappers stay for as long as Objective-C callers need the same C++ objects, and a C++ API built on raw pointers and manual lifetimes still needs annotations or a thin C++ facade before it imports safely.
- Why does Swift warn about a C++ function returning Mesh * when Mesh is a shared reference?ARC must know whether the returned pointer carries a reference it owns. Without `SWIFT_RETURNS_RETAINED` or `SWIFT_RETURNS_UNRETAINED`, Swift 6.4 warns "cannot infer ownership of foreign reference value returned by 'makeMesh()'", because it may insert one retain too many, a leak, or too few, a premature free. Annotate the C++ declaration with the real convention.
- How do you stop the C++ mode from spreading to every module of the app?Put the C++ behind one Swift module that imports it with `internal import`, exposes only Swift types in its public API, and is built with library evolution. Its importers can then build without the C++ mode. If that module's public signatures mention C++ types, every importer must enable the mode.
- Swift imports C++ headers automatically, with no compiler flag.
- Every C++ class imports as a Swift class with reference semantics.
- Enabling the mode in the library target is enough for every importer.
- A non-const C++ method can be called on a Swift let constant.
- Ownership annotations on returned C++ pointers are optional style hints.
Assumes Swift 6.4; C++ interoperability shipped in Swift 5.9 and is still evolving, and -cxx-interoperability-mode=default follows the target's language mode.