Expanding Swift from Apps to Services
#Backend

Expanding Swift from Apps to Services

DevOps Reporter
6 min read

Cory Benfield explores Swift's evolution from an app language to a critical tool for secure, high-scale services, highlighting its memory safety, performance advantages, and interoperability capabilities.

Expanding Swift from Apps to Services

Cory Benfield, Senior Software Engineer at Apple, discusses how Swift has evolved from an app language to a critical tool for secure, high-scale services. He explains how Swift's lack of a garbage collector eliminates tail latency and shares how its "zero-cost abstractions" rival C performance. He shares Apple's roadmap for incremental adoption and demonstrates groundbreaking new interoperability for C++ and Java ecosystems.

Swift's Evolution

In 2014, at Apple's Worldwide Developer Conference, Swift was introduced as a fast, modern, designed-for-safety language enabling high interactivity and development. As an ahead-of-time compiled, memory-safe, multi-paradigm programming language, Swift uses reference counting instead of garbage collection and has recently added support for limited lifetime analysis.

While most developers know Swift as an application programming language for Apple's platforms, people inside and outside of Apple have been using Swift to run services for more than 8 years. The Vapor web framework, written in Swift, started in January 2016. At Apple, services like iCloud Keychain, App Store processing pipelines, SharePlay file sharing, and most recently Private Cloud Compute have been built with Swift.

Private Cloud Compute: A Case Study

Private Cloud Compute allows Apple Intelligence to flex and scale its computational capacity and draw on larger server-based models for complex requests while protecting user privacy. These models run on servers created using Apple Silicon, offering the privacy and security of your iPhone from the silicon up, drawing on the security properties of Swift, and running software with transparency built in.

The service is divided into trusted and untrusted components. Untrusted components are cryptographically prevented from seeing user data, while trusted components can see user data and must be verifiable from the silicon up. This threat model forced Apple to think hard about tools for building trusted components, leading them to choose Swift.

Introduction to Swift

Swift is an imperative programming language focusing on low ceremony and progressive disclosure. It ships with a small standard library containing fundamental data types like strings, arrays, dictionaries, and sets. Swift splits the world into reference and value types.

Classes are reference types where each value points to a single backing location. When implicitly copied, they form another reference to the backing storage, so modifying through one reference causes modification to all other references. Classes enable traditional object-oriented programming patterns with inheritance and dynamic dispatch.

Value types, on the other hand, are independent copies. Each copy is independent of every other copy, and modifications to one copy don't affect any other copy. This applies to Swift structures, enumeration types, and collections. Swift's value semantics are powerful for making code understandable, which is great for services.

Swift Features for Services

Memory Safety: Swift is memory safe by default, enabling complex byte manipulations without unsafe code. This massively reduces exploitable bug density in services exposed to untrusted traffic over the network.

Efficient Memory Usage: Unlike Python, Ruby, or Go, Swift is natively compiled without a garbage collector and is designed to be frugal with memory. This frugality allows better use of hardware. For example, a service moved from Java to Swift with 32GB heaps dropped to below 256MB, reducing hardware requirements by 40%.

Performance: Swift provides great benefits for both latency and throughput. Its lack of a garbage collector eliminates the most common cause of high tail latencies. For base case latency and throughput, Swift's answer is zero-cost abstractions.

Zero-Cost Abstractions: Swift enables writing code that's both safe and performant. The compiler can optimize away safety checks when it proves they're unnecessary. For example, the ChaCha20 stream cipher quarter round written in Swift produces identical assembly to C.

Non-Implicitly Copyable Types: From Swift 5.9, Swift types can declare themselves as non-implicitly copyable, suppressing default copy constructors and enabling unique ownership tracking. This can reduce copies and remove reference counting operations in hot code paths.

Swift's Interoperability

Swift's real superpower is interoperability between languages. From its earliest days, Swift was designed with interoperability in mind.

C Interoperability: Importing C headers and working with C definitions in Swift is straightforward. Swift can call C functions with zero overhead, understand C macros, and even declare inline closures that turn into function pointers. This zero-overhead abstraction gives Swift access to the existing wide world of deployed C code.

C++ Interoperability: Swift learned to interoperate with C++ more recently. All C interop remains, plus Swift understands C++ constructors, unfolds instantiated templates, and can conform C++ types to Swift protocols. Swift can even understand C++ containers as if they were Swift collection types.

Java Interoperability: Swift can host Java libraries inside Swift applications using JNI, and host Swift libraries inside Java applications using the new JEP 454 Foreign Function and Memory interface. Tools like Java2Swift and jextract-swift make bidirectional interoperability possible.

Wrapping Libraries in Safe Interfaces

While direct interoperability is powerful, it's good practice to wrap libraries in safe interfaces. Swift makes this easy. For example, wrapping SQLite involves creating a Swift class that holds the database pointer, implements the constructor with error checking, and adds a deinit for cleanup. The result is a memory-safe wrapper that looks exactly like what you'd want it to look like.

Swift in Private Cloud Compute

Apple's use of Swift in Private Cloud Compute has been a huge success. The Swift components have been incredibly reliable and performed fantastically well. Memory safety was critical for minimizing attack surface. Swift's interoperability enabled integration with cloud-native technologies and platform features like the Secure Enclave. Swift's frugality with memory preserved system memory for inference operations.

Principles for Adopting Swift

Incremental Adoption: Swift can be adopted incrementally as new use cases become available. This might be new components in microservice architectures, new libraries with well-defined API boundaries, new tools or utilities, or replacing older components.

Focus on Value: Look for places where Swift will deliver the most value - great libraries, low memory usage, or performance. Swift's zero startup time and great performance characteristics make it excellent for AWS Lambda and similar technologies.

Enjoy the Process: Swift is a language that leans into the joy of coding. Its focus on low ceremony means you can write the code you want to write instead of the code you have to write.

Getting Started

Getting started with Swift is straightforward. Swift.org has installers and install instructions for supported platforms. Container images are available for those who like containerization. Devcontainers in editors like Visual Studio Code can be valuable for getting started.

Try building something - maybe a gRPC service using gRPC Swift, a client that can hit a gRPC endpoint, or something that interacts with APIs offering OpenAPI specifications. The best way to find out what Swift can do for you is to just try building something.

Remember to have fun doing it. Swift's combination of safety, performance, and interoperability makes it an increasingly compelling choice for services, and Apple's success with Private Cloud Compute demonstrates its viability at scale.

Comments

Loading comments...