swift::String string = "Hello world"; // Not working, the namespace must be Capitalized "Swift::" to work with Swift types.
Currently String
is in the Swift
namespace. The discrepancy between the two namespaces will be corrected soon to correspond to what's in the user manual (so please bear in mind that this is not yet source stable). This should work though:
Swift::String swiftString = "Hello world";
To convert back to std::string
, you can just do an explicit cast:
auto cppString = (std::string) swiftString;
I will update the user guide document to account for that, I think we won't actually offer std::to_string
but will stick to the cast instead.
PS: Any idea about using C++ to Swift on Windows (see my previous post on the Windows issue) ?
On macOS I compile with clang++ using xcrun with the latest installed toolchain, this explain why I don't have to add compile flag to include the path to the C++ interop core headers at <SWIFT_TOOLCHAIN_DIR>/usr/lib/swift. Is my understanding is correct ?
Essentially. On macOS, the open source toolchain you download from swift.org contains both Clang and Swift. In that case, clang from that toolchain is able to find the C++ interop core headers at <SWIFT_TOOLCHAIN_DIR>/usr/lib/swift
because those headers are in the same toolchain as Clang.
However, on Windows if your clang is not in the same toolchain (this also applies to all platforms though, you can recombine compilers across macOS and Linux too), then you must include the path to the core headers.
However, looking at the toolchain directory on Windows there is no interop directory and no headers:
Interesting, I haven't seen this yet. Could you file an issue on GitHub - apple/swift: The Swift Programming Language and we will take a look at this Windows issue.
For now you can copy the headers from your macOS download, they will work on Windows too.
PS2: Question about Swift Structure imported in C++.
Why Swift struct are bridged over as a C++ class
?
In C++ there's no real difference between a class
and a struct
(unlike in Swift), the only difference is the default member access modifier (public
in structs vs private
in class). Thus there would be no difference between us expressing a Swift struct as a class
or a struct
in C++.
Will it be possible at some point to use Swift struct in C++ as C++ struct
?
Well we wouldn't change a class
to a struct
if that's what you mean, for the reason I mentioned above. Accessing Swift properties in Swift structs
will have to go through getters and setters in C++ as well. Does that answer this specific struct
question?