Dunfey · Hotel WWDC as data, est. 1983
Front desk everything
Years
Topics

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 ↗

Transcript all transcripts

Chapters

  • 0:40 — Basics of interoperability
  • 2:22 — Adding Swift to a C++ codebase
  • 4:10 — Calling a C++ method in Swift
  • 4:50 — Calling a Swift method in C++
  • 7:32 — Improving how C++ APIs are imported
  • 12:15 — Foreign reference types

Code shown on screen · 12 snippets

Calling a C++ method from Swift swift · at 4:10 ↗
func loadImage(_ image: UIImage) {
    // Load an image into the shared C++ class.
    CxxImageEngine.shared.pointee.loadImage(image)
}
Import a C++ framework swift · at 4:20 ↗
import CxxImageKit
Import the Generated Header swift · at 4:45 ↗
#import "SampleApp-Swift.h"
Calling a Swift method in C++ swift · at 4:57 ↗
- (IBAction)openPhotoLibrary:(UIButton *)sender {
    // Construct SwiftUI view
    SampleApp::ImagePicker::init().present(self);
}
Using the SWIFT_COMPUTED_PROPERTY attribute cpp · at 8:22 ↗
int  getValue() const SWIFT_COMPUTED_PROPERTY;
void setValue(int newValue);
Using the SWIFT_SHARED_REFERENCE attribute cpp · at 8:42 ↗
struct SWIFT_SHARED_REFERENCE(retain, release) CxxReferenceType;
Using the SWIFT_RETURNS_INDEPENDENT_VALUE attribute cpp · at 8:52 ↗
SWIFT_RETURNS_INDEPENDENT_VALUE 
std::string_view networkName() const;
Using a for-loop to iterate over a C++ std::vector in Swift swift · at 10:45 ↗
// 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 cpp · at 13:54 ↗
#import <swift/bridging>
Applying the SWIFT_SHARED_REFERENCE attribute to CxxImageEngine cpp · at 14:01 ↗
struct SWIFT_SHARED_REFERENCE(IKRetain, IKRelease) CxxImageEngine {
    // ...
};
Applying the SWIFT_COMPUTED_PROPERTY attribute to getImages cpp · at 14:53 ↗
/// \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 swift · at 15:06 ↗
// 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