2023 Developer ToolsSwift
WWDC23 · 18 min · Developer Tools / Swift
Mix Swift and C++
Learn how you can use Swift in your C++ and Objective-C++ projects to make your code safer, faster, and easier to develop. We’ll show you how to use C++ and Swift APIs to incrementally incorporate Swift into your app.
Watch at developer.apple.com ↗Chapters
Code shown on screen · 12 snippets
Calling a C++ method from Swift
func loadImage(_ image: UIImage) {
// Load an image into the shared C++ class.
CxxImageEngine.shared.pointee.loadImage(image)
} Import a C++ framework
import CxxImageKit Import the Generated Header
#import "SampleApp-Swift.h" Calling a Swift method in C++
- (IBAction)openPhotoLibrary:(UIButton *)sender {
// Construct SwiftUI view
SampleApp::ImagePicker::init().present(self);
} Using the SWIFT_COMPUTED_PROPERTY attribute
int getValue() const SWIFT_COMPUTED_PROPERTY;
void setValue(int newValue); Using the SWIFT_SHARED_REFERENCE attribute
struct SWIFT_SHARED_REFERENCE(retain, release) CxxReferenceType; Using the SWIFT_RETURNS_INDEPENDENT_VALUE attribute
SWIFT_RETURNS_INDEPENDENT_VALUE
std::string_view networkName() const; Using a for-loop to iterate over a C++ std::vector in Swift
// Get every image out of the shared C++ class.
for image in CxxImageEngine.shared.pointee.getImages() {
let uiImage = CxxImageEngine.shared.pointee.uiImageFrom(image)
UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
} Import swift/bridging
Applying the SWIFT_SHARED_REFERENCE attribute to CxxImageEngine
struct SWIFT_SHARED_REFERENCE(IKRetain, IKRelease) CxxImageEngine {
// ...
}; Applying the SWIFT_COMPUTED_PROPERTY attribute to getImages
/// \returns all images that have been loaded into the engine. Includes any modifications that were
/// applied to the images.
SWIFT_COMPUTED_PROPERTY
inline std::vector<Image *_Nonnull> getImages() const; Updated for-loop using the "images" computed property
// Get every image out of the shared C++ class.
for image in CxxImageEngine.shared.pointee.images {
let uiImage = CxxImageEngine.shared.pointee.uiImageFrom(image)
UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
} Resources
Related sessions
-
43 min