Why Should Swift "Know" Other Languages?
\n\nImagine you are a head chef in an elite restaurant. You have a signature knife (Swift) — sharp, ergonomic, perfectly balanced in your hand. But to fillet a pufferfish, you need a special scalpel (C), and to create the perfect mousse, an expensive blender (Python). You wouldn't chop the fish with your main knife, would you? The same goes for programming: integrating Swift with other languages is not a sign of weakness, but the pinnacle of mastery.
\n\nThe Swift ecosystem is rapidly evolving, but it doesn't exist in a vacuum. Machine learning libraries are written in Python, high-performance parsers in C, and legacy banking system code in C++. The ability to unite these worlds opens up cosmic possibilities for a developer. In this article, we will break down three key scenarios: how to make Swift friends with Python, C, and C++.
\n\n1. Swift + Python: The Magic of PythonKit
\n\nApple wouldn't be Apple if it didn't make integration as "Swifty" as possible. PythonKit is a framework that allows you to call Python code directly from Swift, as if it were native functions. Setup is simple: just add a dependency via Swift Package Manager.
\n\nProject Setup
\n\nAdd to Package.swift:
let package = Package(\n name: "MySwiftPythonApp",\n dependencies: [\n .package(url: "https://github.com/pvieito/PythonKit.git", branch: "master")\n ],\n targets: [\n .target(name: "MySwiftPythonApp", dependencies: ["PythonKit"])\n ]\n)\n\nExample: Calculating Fibonacci Numbers
\n\nLet's say you have a super-optimized Python script for calculating Fibonacci numbers. Why rewrite it in Swift when you can call it directly?
\n\nPython file (fib.py):
\ndef fib(n):\n a, b = 0, 1\n for _ in range(n):\n a, b = b, a + b\n return a\n\nSwift code:
\nimport PythonKit\n\n// 1. Load the module (without .py)\nlet fibModule = try Python.attemptImport("fib")\n\n// 2. Call the function\nlet result = fibModule.fib(10)\nprint("10th Fibonacci number:", result) // Output: 55\n\n// 3. Work with numpy (if installed)\nlet np = Python.import("numpy")\nlet array = np.array([1, 2, 3, 4])\nprint(array * 2) // Output: [2 4 6 8]\n\nNote: Python.attemptImport is a safe wrapper. If the module is not found, you will get an error, not a crash. Swift and Python integration via PythonKit works on both macOS and Linux (with Python 3.x installed).
When is this needed?
\n- \n
- You need a library that doesn't exist in Swift (e.g.,
pandasorscikit-learn). \n - You are writing a server-side application on Vapor and want to use Python for ETL processes. \n
- You are prototyping an ML model in Python and then embedding it into an iOS app. \n
2. Swift + C: Direct Conversation with the "Hardware"
\n\nC is a legendary language. OS kernels, drivers, and half of the Unix universe are written in it. Swift is designed so that interoperability with C is as painless as possible. You can call functions from any C library without using wrappers.
\n\nImporting C Functions
\n\nCreate a file bridge.h and write the necessary headers into it:
// bridge.h\n#include <math.h>\n#include <string.h>\n\nNow in Swift you can use these functions directly:
\n// Swift\nimport Foundation\n\nlet angle = 45.0 * .pi / 180.0\nlet sine = sin(angle) // C function from math.h\nprint("Sine of 45°:", sine)\n\n// Working with pointers\nlet str = "Hello, C!"\nstr.withCString { cString in\n let length = strlen(cString) // C function\n print("String length:", length)\n}\n\nCreating Your Own C Library
\n\nSup