Swift for Machine Learning: Capabilities and Limitations
The world of machine learning (ML) has traditionally been associated with Python and its libraries (TensorFlow, PyTorch, scikit-learn). However, developers in the Apple ecosystem are increasingly asking: can Swift be used for machine learning tasks? Swift is a powerful, fast, and safe language that underpins all modern applications for iOS, macOS, watchOS, and tvOS. In this article, we will take a detailed look at what tools are available for ML in Swift, what their strengths are, and where they still fall short compared to Python.
We will examine both native Apple frameworks (Create ML, Core ML) and third-party solutions (Swift for TensorFlow). You will learn whether Swift is suitable for production models, training neural networks, or only for inference on devices.
1. Native Apple Tools: Create ML and Core ML
Apple is actively developing its own ecosystem for machine learning. The main frameworks — Create ML and Core ML — are written entirely in Swift and optimized for running on Apple devices.
Create ML — Training Models Without Python
Create ML is a framework that allows you to train machine learning models directly on macOS using only Swift. It is ideal for tasks such as image classification, text analysis, regression, and recommendation systems. The main advantage is the minimal entry barrier: there is no need to install Python, configure CUDA, or delve into complex mathematical abstractions.
Code Example: Training a Text Classifier in Swift
import CreateMLimport Foundation
// Loading data from JSONlet data = try MLDataTable(contentsOf: URL(fileURLWithPath: "reviews.json"))
// Splitting into training and testing setslet (trainingData, testingData) = data.randomSplit(by: 0.8, seed: 5)
// Creating and training the modellet sentimentClassifier = try MLTextClassifier(trainingData: trainingData, textColumn: "text", labelColumn: "label")
// Evaluating accuracylet evaluationMetrics = sentimentClassifier.evaluation(on: testingData)print("Accuracy: \\(evaluationMetrics.classificationError)")
// Saving the model to .mlmodellet metadata = MLModelMetadata(author: "PythonLib User", shortDescription: "Model for sentiment analysis", version: "1.0")try sentimentClassifier.write(to: URL(fileURLWithPath: "SentimentClassifier.mlmodel"), metadata: metadata)This code trains a model on labeled reviews and saves it in the .mlmodel format, which can then be integrated into any iOS/macOS application.
Core ML — Inference on Devices
Core ML is an engine for running machine learning models on Apple devices. It supports models trained in Create ML as well as in TensorFlow or PyTorch (via conversion to the .mlpackage format). Core ML leverages hardware acceleration (Neural Engine, GPU, CPU) and enables the model to work offline, without network latency.
Example: Using a Pre-trained Core ML Model in an Application
import CoreMLimport Vision
// Loading the modelguard let model = try? VNCoreMLModel(for: ResNet50(configuration: MLModelConfiguration()).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 { return } print("Recognized: \\(topResult.identifier) with confidence \\(topResult.confidence)")}
// Performing on the imagelet handler = VNImageRequestHandler(url: URL(fileURL