Swift for Machine Learning: Capabilities and Limitations in Practice
The world of machine learning (ML) has long been associated exclusively with Python — a language with a rich ecosystem of libraries like TensorFlow, PyTorch, and scikit-learn. However, with the growing popularity of iOS and macOS, as well as the emergence of powerful frameworks from Apple, the Swift language is beginning to carve out its niche in ML. In this article, we will examine how suitable Swift is for machine learning tasks, where its strengths lie, and where its critical limitations are, and provide practical code examples.
Why Swift? Key Advantages for ML
Swift is a compiled, statically typed language developed by Apple. Its main advantages for ML are performance and type safety. Unlike Python, which is interpreted and can be slow for heavy computations, Swift compiles to native code, providing a 2–5x speed increase on identical algorithms. Additionally, Swift is perfectly integrated with the Apple ecosystem: Core ML and Create ML allow deploying models directly on users' devices.
Key Frameworks
- Core ML — the primary framework for integrating trained models into iOS/macOS applications. Supports models from TensorFlow, PyTorch, and ONNX.
- Create ML — a tool for training simple models (image classification, text classification, regression) without writing code or with minimal Swift code.
- Swift for TensorFlow (S4TF) — an experimental project by Google that allowed writing neural networks in Swift with full integration with TensorFlow. Unfortunately, the project is frozen, but its ideas live on in other initiatives.
- MLX — a new framework from Apple for on-device machine learning, optimized for Apple Silicon chips.
Practical Example: Image Classification with Core ML
Let's look at a simple example — loading a pre-trained MobileNetV2 model and classifying an image. This code works on iOS and macOS.
import CoreMLimport Visionimport UIKit
// Loading the modelguard let model = try? VNCoreMLModel(for: MobileNetV2().model) else { fatalError("Failed to load model")}
// Creating the requestlet request = VNCoreMLRequest(model: model) { request, error in guard let results = request.results as? [VNClassificationObservation], let topResult = results.first else { print("No results") return } print("Most likely class: \\(topResult.identifier) with confidence \\(topResult.confidence)")}
// Loading the imageguard let image = UIImage(named: "cat.jpg"), let ciImage = CIImage(image: image) else { fatalError("Failed to load image")}
let handler = VNImageRequestHandler(ciImage: ciImage)try? handler.perform([request])This code demonstrates how easy it is to integrate ML into a native application. Everything works "out of the box" without the need for environment setup.
Creating a Model in Swift with Create ML
Create ML allows you to train models directly in Xcode. Here is an example of training a text classifier in Swift:
import CreateMLimport Foundation
// Loading data from JSONlet data = try MLDataTable(contentsOf: URL(fileURLWithPath: "tweets.json"))
// Splitting into training and test setslet (trainingData, testData) = data.randomSplit(by: 0.8, seed: 42)
// Creating and training the modellet classifier = try MLTextClassifier(trainingData: trainingData, textColumn: "text", labelColumn: "sentiment")
// Evaluating accuracylet evaluation = classifier.evaluation(on: testData)print("Accuracy: \\(evaluation.classificationError)")
// Saving the modellet modelURL = URL(fileURLWithPath: "SentimentClassifier.mlmodel")try