Skip to content

[nfc][docs][cxx-interop] Add example in the status document. #41879

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 18, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions docs/CppInteroperability/CppInteroperabilityStatus.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,51 @@ This document provides an overview of the status of the Swift and C++ interopera
Swift has the experimental ability to import a large subset of C++.
This section of the document describes which C++ language and standard library features can be imported and used from Swift in an experimental manner.

### Example
The following example demonstrates several interop features. It compiles and runs on main.

```C++
// cxx-types.h (mapped to CxxTypes module in module.modulemap)
#include <algorithm>
#include <vector>

using V = std::vector<long>;
```

```Swift
// main.swift
import CxxTypes
import std.vector
import std.algorithm

// We can extend C++ types in Swift.
extension V : RandomAccessCollection {
public var startIndex: Int { 0 }
public var endIndex: Int { size() }
}

// Create a vector with some data.
var numbers = V(4)
std.fill(numbers.beginMutating(), numbers.endMutating(), 41)

// Transform it using C++.
std.transform(numbers.beginMutating(), numbers.endMutating(),
numbers.beginMutating()) { (element: Int) in
return element + 1
}

// Loop over it in Swift.
for (index, element) in numbers.enumerated() {
print("v[\(index)] = \(element)")
}

// We can also use anything in RandomAccessCollection, such as map and zip.
let strings = numbers.map { "\($0)" }
for (s, n) in zip(strings, numbers) {
print("\(s) = \(n)")
}
```

### Importing C++

There are currently two experimental ways to import C++ into Swift:
Expand Down