Machine Learning in Swift: Libraries for iOS/macOS
Swift is a powerful and intuitive language from Apple, actively used not only for developing applications for iOS and macOS but also for machine learning tasks. Thanks to its performance, type safety, and direct integration with Apple frameworks, Swift is becoming an excellent choice for deploying ML models on devices. In this article, we will review the key libraries and tools for machine learning in Swift that will help you create smart applications for the Apple ecosystem.
1. Core ML — Apple's flagship framework
Core ML is Apple's primary framework for integrating machine learning models into applications. It supports a large number of model formats (MLModel, ONNX, TensorFlow, PyTorch) and is optimized for on-device performance (iPhone, iPad, Mac). Core ML automatically uses the Neural Engine, GPU, and CPU for maximum performance.
Example: Image classification with Core ML
import CoreMLimport Vision
// Load the pre-trained MobileNetV2 modelguard let model = try? VNCoreMLModel(for: MobileNetV2(configuration: MLModelConfiguration()).model) else { fatalError("Failed to load model")}
// Create a requestlet request = VNCoreMLRequest(model: model) { request, error in guard let results = request.results as? [VNClassificationObservation], let topResult = results.first else { print("Failed to classify") return } print("Object: \\(topResult.identifier) with confidence \\(topResult.confidence)")}
// Load the imageguard let image = UIImage(named: "cat.jpg"), let ciImage = CIImage(image: image) else { return }
let handler = VNImageRequestHandler(ciImage: ciImage, options: [:])try? handler.perform([request])2. Create ML — training without code (and with code)
Create ML is an Apple tool for training machine learning models directly in Xcode. It supports tasks such as image classification, text classification, tabular data, recommendation systems, and even sound classifiers. Models trained in Create ML are automatically exported to the .mlmodel format and are ready for use with Core ML.
Example: Training a text classification model
import CreateML
// Load data from CSVlet data = try MLDataTable(contentsOf: URL(fileURLWithPath: "/path/to/data.csv"))
// Split into training and testing setslet (trainingData, testingData) = data.randomSplit(by: 0.8, seed: 42)
// Create a text classifierlet classifier = try MLTextClassifier(trainingData: trainingData, textColumn: "text", labelColumn: "label")
// Evaluate accuracylet evaluationMetrics = classifier.evaluation(on: testingData)print("Accuracy: \\(evaluationMetrics.classificationError)")
// Save the modellet metadata = MLModelMetadata(author: "PythonLib", shortDescription: "Review classifier", version: "1.0")try classifier.write(to: URL(fileURLWithPath: "/path/to/SentimentClassifier.mlmodel"), metadata: metadata)3. TensorFlow Lite (TFLite Swift) — mobile TensorFlow
TensorFlow Lite is a lightweight version of TensorFlow for mobile and embedded devices. The Swift interface allows loading and running TFLite models on iOS and macOS. TFLite supports hardware acceleration via Metal Performance Shaders (MPS) and Core ML delegates.
Example: Running a TFLite model
import TensorFlowLite
// Load the modelguard let modelPath = Bundle.main.path(forResource: "mobilenet_v1_1.0_224", ofType: "tflite") else { fatalError("Model not found")}
let interpreter = try Interpreter(modelPath: modelPath)try interpreter.allocateTensors()
// Prepare input data (e.g., 224x224 image)let inputData: Data = preprocessImag