Swift for Machine Learning: Capabilities and Limitations in Practice
\n\nThe world of machine learning (ML) has long been associated exclusively with Python. However, with the growing popularity of iOS/macOS development and the emergence of powerful frameworks from Apple, the Swift language is increasingly entering this field. In this article, we will examine how suitable Swift is for ML tasks, what tools it offers, where its use is justified, and where it still falls short of classic Python.
\n\nWhy Swift? Apple Ecosystem and Performance
\n\nSwift is a compiled language with a strict type system and high performance close to C++. For machine learning, this offers several key advantages:
\n- \n
- Execution speed: native computation without interpreter overhead. \n
- Integration with Apple platforms: direct access to Metal (GPU), Neural Engine, Accelerate framework. \n
- Memory safety: fewer runtime errors compared to Python. \n
However, the main driver is Apple's ambition to make ML accessible to mobile developers. Instead of learning Python and deploying models separately, an iOS developer can stay within the native Xcode environment.
\n\nKey Frameworks
\nApple provides three main tools for working with ML in Swift:
\n- \n
- Core ML — a runtime for running models on the device. \n
- Create ML — a framework for training models without Python. \n
- MLX (Apple's open-source project) — for more in-depth research. \n
Running Pre-trained Models with Core ML
\nThe most common scenario is integrating a pre-trained model into a mobile application. Swift excels here: the code is minimal and intuitive.
\n\nExample of image classification using Core ML and Vision:
\nimport Vision\nimport CoreML\n\n// 1. Load the model (e.g., MobileNetV2)\nguard let model = try? VNCoreMLModel(for: MobileNetV2().model) else {\n fatalError("Failed to load model")\n}\n\n// 2. Create a request\nlet request = VNCoreMLRequest(model: model) { request, error in\n if let results = request.results as? [VNClassificationObservation] {\n // Print top-3 predictions\n for result in results.prefix(3) {\n print("\\(result.identifier): \\(result.confidence * 100)%")\n }\n }\n}\n\n// 3. Execute the request on an image\nguard let image = UIImage(named: "cat.jpg"),\n let ciImage = CIImage(image: image) else { return }\n\nlet handler = VNImageRequestHandler(ciImage: ciImage)\ntry? handler.perform([request])\n\nAs you can see, Swift allows inference in 10-15 lines of code. Everything runs natively, using the GPU or Neural Engine.
\n\nTraining Models with Create ML
\nCreate ML is Apple's attempt to make model training accessible to regular developers. You can train image classifiers, text classifiers, tabular data, and even recommendation models without leaving Swift.
\n\nExample: Training a Text Classifier
\nSuppose we have a CSV file with reviews and labels (positive/negative). Training looks like this:
\nimport CreateML\nimport Foundation\n\n// 1. Load the data\nlet data = try MLDataTable(contentsOf: URL(fileURLWithPath: "reviews.csv"))\n\n// 2. Split into training and testing sets\nlet (trainingData, testingData) = data.randomSplit(by: 0.8, seed: 42)\n\n// 3. Create a classifier\nlet classifier = try MLTextClassifier(trainingData: trainingData,\n textColumn: "text",\n labelColumn: "label")\n\n// 4. Evaluate accuracy\nlet evaluation = classifier.evaluation(on: testingData)\nprint("Accuracy: \\(evaluation.classificationError * 100)%")\n\n// 5. Save the model for Core ML\ntry class