What's new in C++ Interoperability in Swift 5.9
Introduction
- For some types of APIs, Swift 5.9 provides bidirectional compatibility with C++ and Objective-C++.
- Swift 5.9 introduced direct interoperability between Swift and C++ types and functions.
Implementation
Configuration
Step 1: Build Settings > Swift Complier - Language > C++ and Objective-C Interoperability > Select C++/Objective-C++
Step 2: Import C++ file i.e [Employee.cpp] into the Bridging Header
1
#import "Employee.cpp"
Calling C++ in Swift
In this example, you define a structure called Employee with two parameters: name of type std::string and age of type int. The initializer is defined using a constructor that takes the name and age as parameters and initializes the corresponding member variables.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
struct Employee {
std::string name;
int age;
// Initializer
Employee(const std::string& empName, int empAge) : name(empName), age(empAge) {}
};
And in Swift file create an instance of Employee named emp using the initializer by passing the name “Jacob” and age 30 as arguments. You then access and print the employee’s name and age using the emp.name and emp.age member variables, respectively.
1
2
3
4
5
func createEmployee() {
let emp = Employee("Jacob", 30)
print(emp.name)
print(emp.age)
}
References
- https://www.swift.org/blog/swift-5.9-released/
- https://forums.swift.org/t/c-interoperability-in-swift-5-9/65369
This post is licensed under CC BY 4.0 by the author.