@@ -8,6 +8,51 @@ This document provides an overview of the status of the Swift and C++ interopera
8
8
Swift has the experimental ability to import a large subset of C++.
9
9
This section of the document describes which C++ language and standard library features can be imported and used from Swift in an experimental manner.
10
10
11
+ ### Example
12
+ The following example demonstrates several interop features. It compiles and runs on main.
13
+
14
+ ``` C++
15
+ // cxx-types.h (mapped to CxxTypes module in module.modulemap)
16
+ #include < algorithm>
17
+ #include < vector>
18
+
19
+ using V = std::vector<long >;
20
+ ```
21
+
22
+ ``` Swift
23
+ // main.swift
24
+ import CxxTypes
25
+ import std .vector
26
+ import std .algorithm
27
+
28
+ // We can extend C++ types in Swift.
29
+ extension V : RandomAccessCollection {
30
+ public var startIndex: Int { 0 }
31
+ public var endIndex: Int { size () }
32
+ }
33
+
34
+ // Create a vector with some data.
35
+ var numbers = V (4 )
36
+ std.fill (numbers.beginMutating (), numbers.endMutating (), 41 )
37
+
38
+ // Transform it using C++.
39
+ std.transform (numbers.beginMutating (), numbers.endMutating (),
40
+ numbers.beginMutating ()) { (element : Int ) in
41
+ return element + 1
42
+ }
43
+
44
+ // Loop over it in Swift.
45
+ for (index, element) in numbers.enumerated () {
46
+ print (" v[\( index ) ] = \( element ) " )
47
+ }
48
+
49
+ // We can also use anything in RandomAccessCollection, such as map and zip.
50
+ let strings = numbers.map { " \( $0 ) " }
51
+ for (s, n) in zip (strings, numbers) {
52
+ print (" \( s ) = \( n ) " )
53
+ }
54
+ ```
55
+
11
56
### Importing C++
12
57
13
58
There are currently two experimental ways to import C++ into Swift:
0 commit comments