Swift.org's Avatar

Swift.org

@swift.org.web.brid.gy

Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns. [bridged from https://swift.org/ on the web: https://fed.brid.gy/web/swift.org ]

129 Followers  |  0 Following  |  461 Posts  |  Joined: 12.09.2024  |  3.3984

Latest posts by swift.org.web.brid.gy on Bluesky

ICYMI: Memory Safety, Ecosystem Talks, and Java Interoperability at FOSDEM 2025 The Swift community had a strong presence at FOSDEM 2025, the world’s largest independently run open source conference, held every year in Brussels, Belgium. FOSDEM highlighted a range of Swift-related talks related to memory safety, a broad ecosystem around Swift including using it to develop web services and embedded projects, and new areas of the project including Java interoperability. In case you missed it, here are a few highlights from the event: ## Memory Safety in Swift The main track of the conference featured a talk presented by Doug Gregor on memory safety: “Incremental Memory Safety in an Established Software Stack: Lessons Learned from Swift.” If you’re interested in learning more about Swift’s memory safe features, this talk is a great place to start; it walks through the different dimensions of memory safety in Swift, the language’s safe interoperability with C(++), and reflects on lessons learned for both programming language design and adopting Swift in an established software codebase. To learn more about memory safety in Swift, see the Swift documentation page on memory safety, as well as the vision document on memory safety. ## Swift DevRoom FOSDEM is primarily organized into DevRooms, volunteer-organized conference tracks around technical communities and topics. This year Swift celebrated its inaugural DevRoom organized by a local community member, Steven Van Impe, with contributions from a large group of volunteers including proposal reviewers, speakers, and day-of-operations support. Swift’s first Swift DevRoom was a hit! 🎉 The room was packed with 12 talks, covering a wide range of topics and demos from the Swift ecosystem: talks related to running Swift on Linux, showcasing various IDEs like VS Code, and a whole hour dedicated to embedded content. A few talks to highlight from the event: * Building a Ferrofluidic Music Visualizer with Embedded Swift * Building container images with swift-container-plugin * Distributed Tracing in Server-Side Swift Check out the complete lineup to learn more! ## Java Interoperability In the Free Java DevRoom, Konrad ‘ktoso’ Malawski presented on Java interoperability in Swift: “Foreign Function and Memory APIs and Swift/Java interoperability.“ Konrad’s talk was a technical deep dive into the Java interoperability effort that launched in 2024, demonstrating the bridges and bindings needed to integrate systems written in Swift and Java while still maintaining great performance. Catch up on this talk to see how you can leverage existing libraries without complete rewrites. Work in early development has been released on GitHub for feedback and contributions, and your feedback is welcome on the forums.
06.08.2025 18:15 — 👍 0    🔁 0    💬 0    📌 0
Announcing Swift 6 We’re delighted to announce the general availability of Swift 6. This is a major new release that expands Swift to more platforms and domains. Many people know of Swift as a language for app development, with a million apps on the App Store. But Swift is great for more than just apps. Swift’s safety, speed, and approachability make it a great choice for many other use cases including libraries, internet-scale services, and the most performance-critical and secure code. Swift 6 scales even further through new low-level programming features, an embedded Swift language subset, expanded Linux and Windows support, new cross-platform APIs including the new Swift Testing library, and more. Read on for a deep dive into changes to the language, standard libraries, debugging, platform support, and next steps for getting started with Swift 6. ## Language and Standard Library ### Concurrency Swift has long offered memory safety, ensuring that variables are initialized before they’re used, memory isn’t accessed after it’s been deallocated, and array indices are checked for out-of-bounds errors. Swift 6 now includes a new, opt-in language mode that extends Swift’s safety guarantees to prevent data races in concurrent code by diagnosing potential data races in your code as compiler errors. Data-race safety checks were previously available as warnings in Swift 5.10 through the `-strict-concurrency=complete` compiler flag. Thanks to improved `Sendable` inference and new compiler analysis for transferring mutable state from one actor to another, Swift 6 warnings about data-race safety have fewer false positives. You can find more information about the Swift 6 language mode and how to migrate at Swift.org/migration. Swift 6 marks the start of the journey to make data-race safety dramatically easier. The usability of data-race safety remains an area of active development, and your feedback will help shape future improvements. Swift 6 also comes with a new Synchronization library for low-level concurrency APIs, including atomic operations and a new mutex API. ### Typed throws Swift 6 enables functions to specify the type of error that they throw as part of their signature. This feature is useful in generic code that forwards along errors thrown in client code, or in resource-constrained environments that cannot allocate memory, such as in embedded Swift code. For example: func parseRecord(from string: String) throws(ParseError) -> Record { // ... } A call to `parseRecord(from:)` will either return a `Record` instance or throw an error of type `ParseError`. A `do..catch` block will infer `ParseError` as the type of the `error` variable: do { let record = try parseRecord(from: myString) } catch { // 'error' has type 'ParseError' } Typed throws generalizes over throwing and non-throwing functions. A function that is specified as `throws` (without a specific error type) is equivalent to one that specifies `throws(any Error)`, whereas a non-throwing function is equivalent to one that specifies `throws(Never)`. Calls to functions that are `throws(Never)` are non-throwing and don’t require error handling at the call site. Typed throws can also be used in generic functions to propagate error types from parameters, in a manner that is more precise than `rethrows`. For example, the `Sequence.map` method can propagate the thrown error type from its closure parameter, indicating that it only throws the same type of errors as the closure: extension Sequence { func map<T, E>(_ body: (Element) throws(E) -> T) throws(E) -> [T] { // ... } } When given a closure that throws `ParseError`, `map` will throw `ParseError`. When given a non-throwing closure, `E` is inferred to `Never` and `map` will not throw. ### Ownership Swift 5.9 introduced non-copyable types with the `~Copyable` syntax for modeling resources with unique ownership, and writing performance-conscious code by eliminating the runtime overhead associated with copying. Swift 6 now supports these types with the generics system, making it possible to write generic code that works with both copyable and non-copyable types. For example: protocol Drinkable: ~Copyable { consuming func use() } struct Coffee: Drinkable, ~Copyable { /* ... */ } struct Water: Drinkable { /* ... */ } func drink(item: consuming some Drinkable & ~Copyable) { item.use() } drink(item: Coffee()) drink(item: Water()) The `Drinkable` protocol has no requirement that its conforming types are `Copyable`. This means both the non-copyable type `Coffee` and copyable type `Water` can be passed into the generic `drink` function. Switch statements can now be written to avoid copying within enum pattern-matching operations. This means that switch statements can be used with non-copyable payloads and can also provide performance benefits for copyable payloads, especially those based on copy-on-write containers like `Array` and `Dictionary`. Non-copyable types are already used throughout the standard libraries. For instance, the new `Atomic` type in the Synchronization library is based on `~Copyable`, `Optional` and `Result` can now wrap non-copyable types, and the unsafe buffer pointer types can now point to non-copyable elements. C++ interoperability also uses non-copyable types to expose C++ move-only types to Swift. ### C++ interoperability Swift 5.9 introduced bidirectional interoperability with C++ to seamlessly bring Swift to more existing projects. Swift 6 expands interoperability support to C++ move-only types, virtual methods, default arguments, and more standard library types including `std::map` and `std::optional`. C++ types that do not have a copy constructor can now be accessed from Swift 6 as non-copyable types with `~Copyable`. And for those times when it’s useful to expose a C++ type with a copy constructor as `~Copyable` in Swift for better performance, a new `SWIFT_NONCOPYABLE` annotation can be applied to the C++ type. Swift now also supports calls of C++ virtual methods on types annotated as `SWIFT_SHARED_REFERENCE` or `SWIFT_IMMORTAL_REFERENCE`. When calling C++ functions or methods that have default argument values for some of their parameters, Swift now respects these default values, rather than requiring you to explicitly pass an argument. ### Embedded Swift Swift 6 includes a preview of Embedded Swift, a language subset and compilation mode suitable for embedded software development, such as programming microcontrollers. The toolchain supports ARM and RISC-V bare-metal targets. Embedded Swift produces small and standalone binaries by relying on generic specialization. Since it doesn’t rely on a runtime or type metadata, Embedded Swift is suitable for platforms with tight memory constraints as well as use in low-level environments with limited runtime dependencies. Embedded Swift remains an experimental feature, with ongoing development before stable support in a future Swift release. ### 128-bit Integers Swift 6 rounds out the set of low-level integer primitives with the addition of signed and unsigned 128-bit integer types. These are available on all Swift platforms, and provide the same API as other fixed-width integer types in the standard library. ### Productivity enhancements Swift 6 introduces a number of productivity enhancements, including `count(where:)` to streamline counting the number of elements in a sequence that satisfy a predicate, pack iteration for writing natural `for`-loops over the elements in a value parameter pack, access control for imports to keep implementation details from leaking into your public APIs, `@attached(body)` macros for synthesizing and augmenting function implementations, expression macros as default arguments, and more. You can find a complete list of language proposals that were accepted through the Swift Evolution process and implemented in Swift 6 on the Swift Evolution dashboard. ## Debugging ### Custom LLDB summaries with `@DebugDescription` @DebugDescription` section" href="#custom-lldb-summaries-with-debugdescription"> Swift 6 provides a new debugging macro to easily customize how an object is displayed in LLDB when using the `p` command, and in the variables view in Xcode and VSCode, by using a formatting scheme that does not run arbitrary code. Types that conform to `CustomDebugStringConvertible` provide a `debugDescription` property that returns a string describing the object. In LLDB, the `po` command calls this computed property on an object. In contrast, the `p` command uses LLDB’s type summary formatters to directly format the object using its stored property values. `@DebugDescription` is a new macro in the standard library which lets you specify LLDB type summaries for your own types directly in code. The macro processes the `debugDescription` property, translating simple string interpolations involving stored properties into LLDB type summaries. This allows LLDB to use your custom formatting even when using `p`, and also in Xcode or VSCode’s variable display windows. The macro can use an existing conformance to `CustomDebugStringConvertible`, or you can provide a separate string interpolation only for use in LLDB’s `p` command. Providing a separate LLDB description string is useful if your `CustomDebugStringConvertible` implementation doesn’t meet the requirements of the `@DebugDescription` macro, or if you’re familiar with the LLDB Summary String syntax and you want to use it directly. For example, the following code customizes how `po` in LLDB displays the `Organization` type with a conformance to `CustomDebugStringConvertible`, and the `@DebugDescription` macro exposes this custom formatting to the `p` command and the variables view: @DebugDescription struct Organization: CustomDebugStringConvertible { var id: String var name: String var manager: Person // ... and more var debugDescription: String { "#\(id) \(name) [\(manager.name)]" } } (lldb) p myOrg (Organization) myOrg = "`#100 Worldwide Travel [Jonathan Swift]`" ### Improved startup performance with explicit modules Swift 6 dramatically improves startup performance in the debugger when you use explicit module builds. When debugging locally-built code, LLDB can now import explicitly-built Swift and Clang modules directly from the project build artifacts. This avoids the need to recompile implicit Clang module dependencies from source, which can take a long time, and it’s very sensitive to issues with header search paths. If the first `p` or `po` command in LLDB takes a long time due to Clang module compilation, or if your debugging is frequently blocked by Clang header import problems, consider adopting explicit modules in your project! ## Libraries ### Foundation Swift 6 unifies the implementation of Foundation across all platforms. The modern, portable Swift implementation provides consistency across platforms, it’s more robust, and it’s open source. macOS and iOS started using the Swift implementation of Foundation alongside Swift 5.9, and Swift 6 brings these improvements to Linux and Windows. Core types like `JSONDecoder`, `URL`, `Calendar`, `FileManager`, `ProcessInfo`, and more have been completely reimplemented in Swift. These types share their implementation with macOS 15 and iOS 18, providing a new level of cross-platform consistency, reliability, and performance. Recently released APIs like `FormatStyle`, `ParseStrategy`, `Predicate`, and `JSON5`, from past macOS and iOS releases are now available on all Swift platforms. New Foundation APIs like `Expression`, calendar enumeration improvements, calendar recurrence rules, format style enhancements, and more are available simultaneously on macOS, iOS, Linux, and Windows - and they were built with community involvement. If your Linux or Windows app imports the `Foundation` library from the Swift toolchain today, you get all of these improvements for free. And if your app is particularly sensitive to binary size, you can now import the `FoundationEssentials` library, which provides a more targeted subset of Foundation’s features that omits internationalization and localization data. ### Swift Testing Swift 6 introduces Swift Testing, a new testing library designed from the ground up for Swift. It includes expressive APIs that make it easy to write and organize tests. It provides detailed output when a test fails using macros like `#expect`. And it scales to large codebases with features like parameterization to easily repeat a test with different arguments. For example: @Test("Continents mentioned in videos", arguments: [ "A Beach", "By the Lake", "Camping in the Woods" ]) func mentionedContinents(videoName: String) async throws { let videoLibrary = try await VideoLibrary() let video = try #require(await videoLibrary.video(named: videoName)) #expect(video.mentionedContinents.count <= 3) } Swift Testing takes full advantage of macros. Its `@Test` and `@Suite` attached macros declare test functions and suite types respectively, and they accept arguments (known as traits) to customize various behaviors. The `#expect` and `#require` expression macros validate expected behaviors, and capture rich representation of expressions and their sub-values to produce detailed failure messages. Since Swift Testing is included directly in Swift 6 toolchains, you can `import Testing` without needing to declare a package dependency. This means your tests do not need to build Swift Testing or its dependencies (including swift-syntax), and its macro implementation comes prebuilt. The package manager in Swift 6 automatically builds and runs Swift Testing tests in addition to XCTests (if present), and shows results from both libraries in log output. Swift Testing supports all platforms that Swift officially supports, including all Apple platforms, Linux, and Windows. To learn more about this new open source project, visit the swift-testing repository on GitHub, and get involved with its ongoing development on the forums. ## Platform Support Swift is designed to support development and execution on all major operating systems, and platform consistency and expansion underpins Swift’s ability to reach new programming domains. Swift 6 brings major improvements to Linux and Windows across the board, including support for more Linux distributions and Windows architectures. Toolchains for all of the following platforms are available for download from Swift.org/install. ### Fully static SDK for Linux Swift 6 supports building fully statically linked executables for Linux; these have no external dependencies, so they are ideal for situations where you want to copy a program directly onto a system or into a container and run it without installing any extra software. The SDK can also be used to cross-compile to Linux from other platforms. Learn how to get started with the static SDK for Linux on Swift.org. ### New Linux distributions Swift 6 adds official support and testing for Debian and Fedora, as well as on Ubuntu 24.04. ### Windows build performance Prebuilt toolchains are now available for the arm64 architecture, which provides improved compiler performance for Windows on ARM hosts. In Swift 6, the Swift package manager also parallelizes builds across multiple cores on Windows by default. On a 10-core machine, this can improve build performance by up to a factor of 10! ## Next Steps ### Download Swift 6 You can try out these exciting new developments in Swift 6 today! Install the official Swift 6 toolchains for macOS, Linux, and Windows at Swift.org/install. ### Get started with Swift The Swift Programming Language book has been updated to reflect the latest Swift 6 syntax and features. It serves as the official Swift guide and an excellent starting point for learning the language. To help kickstart your Swift journey, Swift.org/getting-started offers tutorials for various use cases, including building a cross-platform library, a web service using Vapor, and an embedded application for a microcontroller. There are also articles for diving deeper into some of Swift’s most popular features. ### Explore the package ecosystem The Swift package ecosystem is continuously growing with new technologies to help you with a variety of tasks in your projects. You can explore package highlights at Swift.org/packages, which features popular package categories and a selection of new and notable packages that are hand-curated from an open nomination process every month. ### Get involved Your experience with Swift 6 and your feedback can help shape the future evolution of the language, the tools, the package ecosystem, and the community. You can get involved by sharing your packages, documentation improvements, educational content, bug reports and enhancement requests, code contributions, and participating in forum discussions. Learn more at Swift.org/contributing. Swift 6 is the culmination of countless contributions from members across the Swift community, and it marks a decade of building this incredible language, ecosystem, and community together. Thank you to everyone who participated in development and provided feedback. Your contributions make Swift a better language.
06.08.2025 18:10 — 👍 1    🔁 0    💬 0    📌 0
The Next Chapter in Swift Build Technologies Swift continues to grow in popularity as a cross-platform language supporting a wide variety of use cases, with support on a variety of embedded devices, form factors that encompass wearables to server, and a wide variety of operating systems. As Swift expands, there’s value in investing in matching cross-platform build tools that provide a powerful, consistent, and flexible experience across the ecosystem. As a foundational step in this new chapter of Swift build technologies, today Apple is open sourcing Swift Build, a powerful and extensible build engine that provides a set of build rules for building Swift projects. Swift Build is the engine used by Xcode, which supports millions of apps in the App Store as well as the internal build process for Apple’s own operating systems. The open source repository also includes support for targeting Linux and Windows. ## Introducing Swift Build The primary responsibility of the build system is to transform user-authored inputs (such as a project description and source code) into output artifacts like command line tools, libraries, and applications. Build systems play an important role in providing a great developer experience, enabling higher level features which determine how users architect and work with their projects. Furthermore, the performance and reliability of a build system has a direct impact on developer productivity. Swift Build is an infrastructural component designed to plan and execute builds requested by a higher-level client like Swift Package Manager or Xcode. It builds on top of the existing llbuild project to add capabilities including: * Robust integration with the Swift compiler to reliably and efficiently coordinate the build of Swift projects * Support for a wide variety of product types including libraries, command line tools, and GUI applications with advanced build configuration options * Build graph optimizations that maximize parallelism when building Swift and C code ## Roadmap for Swift Build Compared to the build engine in Xcode, the build engine in Swift Package Manager is fairly simple. On Apple platforms, having two different ways to build packages has also led to user confusion when the two implementations’ behavior didn’t match. Contributing Xcode’s build engine to the Swift project and developing it in open source alongside the Swift compiler provides the tools necessary to address these problems and deliver a great builds experience to all Swift users. With this release, SwiftPM now has the opportunity to offer a unified build execution engine across all platforms. This change should be transparent to users and maintain full compatibility with all existing packages while delivering a consistent cross-platform experience. At the same time, it lays the foundation to enable new features and improvements across all platforms and tools, and unlocks new performance optimizations and developer-facing features. As a small first step towards this vision, today the team is submitting a pull request to begin the process of integrating support for Swift Build in SwiftPM as an alternate build engine. In the coming months, we’d like to collaborate with the community to complete the work of unifying build system integrations so users can benefit from future tooling improvements across all platforms and project models. We believe this is an important step in continuing to enable a healthy package ecosystem where developers can rely on a consistent, polished development experience — no matter what IDE they’re using or platform they’re targeting. We’ll be sharing more details about this work on the Swift forums, and we’re looking forward to hearing others’ feedback! ## An invitation to participate We look forward to working with the community to continue evolving how we build Swift code. You can find the `swift-build` repository in the Swift organization on GitHub, including a README and documentation describing how to build and contribute. Contributions via pull requests and issues are welcome, and we’d also love to solicit feedback and ideas for improvements on the Swift forum. This is an exciting new chapter for Swift’s build system, and we’re looking forward to all the potential it opens for Swift!
06.08.2025 18:10 — 👍 0    🔁 0    💬 0    📌 0
How Swift's server support powers Things Cloud You might be familiar with Things, a delightful personal task manager that has won two Apple Design Awards and is available across Apple devices including iPhone, iPad, Mac, Apple Watch, and Apple Vision Pro. At Cultured Code, the team behind Things, we care about a great user experience across every aspect of the product. This extends to our server back end, and after a rewrite our Things Cloud service has transitioned entirely to Swift. Over the past year in production, Swift has consistently proven to be reliable, performant, and remarkably well-suited for our server-side need. Things Cloud serves as the backbone of the app’s experience, silently synchronizing to-dos across devices. The robustness of this work is ensured by a rigorous theoretical foundation, inspired by operational transformations and Git’s internals. After twelve years in production, Things Cloud has earned our users’ trust in its reliability. But despite the enduring strength of the architecture itself, the technology stack lagged behind. Things Cloud synchronizes to-dos across different devices. ## Switching to Swift Our legacy Things Cloud service was built on Python 2 and Google App Engine. While it was stable, it suffered from a growing list of limitations. In particular, slow response times impacted the user experience, high memory usage drove up infrastructure costs, and Python’s lack of static typing made every change risky. For our push notification system to be fast, we even had to develop a custom C-based service. As these issues accumulated and several deprecations loomed, we realized we needed a change. A full rewrite is usually a last resort, but in our case, it was the only viable path for Things Cloud. We explored various programming languages including Java, Python 3, Go, and even C++. However, Swift – which was already a core part of our client apps – stood out for its potential and unique benefits. Swift promised excellent performance, predictable memory management through ARC, an expressive type system for reliability and maintainability, and seamless interoperability with C and C++. While we initially had concerns that Swift’s server support wasn’t as mature as that found in other ecosystems, both Apple and the open-source community had shown strong commitment to its evolution. Swift had reliably compiled on Linux for a long time; the Swift Server workgroup had coordinated server efforts since 2016; the SwiftNIO library gave us confidence in the foundational capabilities, and Vapor provided all the tools to get us up and running quickly. Convinced by these benefits and the opportunity to use the same language for client and server development, we embarked on a three-year journey to rewrite Things Cloud. We’ve been using it internally for the past two years, and it has now been live in production for over a year. ## The new Swift-based service architecture We’ll outline the core components of our new service architecture, highlighting the Swift packages we use. We’ve found that these components work well together to provide reliability and stability, and we believe this serves as a valuable reference point for others considering a similar transition to Swift. Overview of our new Swift-based service architecture. ### Code * Our **Swift** server codebase has around 30,000 lines of code. It produces a binary of 60 MB, and builds in ten minutes. * It uses **Vapor** as an HTTP web framework, which uses **SwiftNIO** as its underlying network application framework. * We compile a single “monolith” binary from our Swift source code, but use it to run multiple services, each configured by passing different parameters at runtime. * We use **Xcode** for its robust suite of tools for development, debugging, and testing. It provides us with a familiar and consistent experience across both server and client environments. ### Deployment * **AWS** hosts our entire platform, and is entirely managed by **Terraform** , an infrastructure as code tool. * We use a continuous integration pipeline to automate tests and build our Swift code into a **Docker** image. This is then deployed in a **Kubernetes** cluster alongside other components. * The **HAProxy** load balancer is used to route client traffic to the appropriate Swift service in the cluster. ### Storage * Persistent data is stored in **Amazon Aurora MySQL** , a relational database, which we connect to with **MySQLKit**. * To keep the database small, we’re offloading less-used data to **S3** , which we access via the **Soto** package. * More ephemeral data, such as push notifications and caches, is stored in **Redis** , an in-memory key-value database, which we access via **RediStack**. ### Other Services * The **APNSwift** package is used to communicate with the Apple Push Notification service. * **AWS Lambda** , a serverless compute service, powers our **Mail to Things** feature. This process is written in Python 3 due to its mature libraries for the processing of incoming emails. The results are passed to Swift using **Amazon Simple Queue Service**. ### Monitoring * We take the resilience of Things Cloud seriously and go to great lengths to ensure it. * In Swift, we generate JSON logs using our own logger. To produce metrics, we’re using the **Swift Prometheus**. * We use **Amazon CloudWatch** to store and analyze logs and metrics. It triggers Incidents, which reach the responsible engineer via **PagerDuty**. * To test how well our service can recover from transient errors, we employ **chaos testing**. Each day, our self-written chaos agent performs random disruptive actions such as terminating a Swift service or restarting the database. We then verify that the system recovers as expected. ## Results We wanted to thoroughly test the performance and stability of the new Swift service architecture before it was deployed in production. So during the development phase, we deployed the new system alongside the existing legacy system. While the legacy system continued to be the operational service for all requests, the new system also processed them independently using its own logic and database. This approach enabled us to develop and test the new system under real-world conditions without any risk to the user experience. Thanks to the confidence we built in the new system’s robustness and reliability through evaluating it with production workloads, we were able to deploy a hardened system from the very beginning. Now, with over a full year in production, we’re pleased to report that Swift has fulfilled its promise for server-side development. It’s fast and memory-efficient. Our Kubernetes cluster comprises four instances, each with two virtual CPUs and 8 GB of memory, and has handled traffic peaks of up to 500 requests per second. Compared to the legacy system, this setup has led to a more than threefold reduction in compute costs, while response times have shortened dramatically. Comparison between our legacy service and new Swift-based one. And one extra win: Swift’s outstanding performance allowed us to replace our custom C-based push notification service with a Swift-based one; this significantly simplified our codebase and operations. ## Conclusions Swift turned out to be a great choice for server usage. It delivered on everything we had hoped for: We’re now using a modern and expressive programming language, the code runs and performs well, and the Swift ecosystem provides all the integrations we need. With a year of production use, we haven’t encountered a single operational issue. For more information on our journey and experiences, you might enjoy our recent talk at the ServerSide.Swift conference. We encourage other teams to consider using Swift for server-oriented projects. While we chose to undergo a complete rewrite, the gradual adoption of Swift is also an intriguing option, especially considering the recently announced initiative aimed at enhancing Java interoperability. As for us, we believe our server architecture is in its best shape ever, and we’re thrilled about the new features we can build upon this solid foundation.
06.08.2025 18:10 — 👍 1    🔁 0    💬 0    📌 0
Introducing gRPC Swift 2 Say hello to gRPC Swift 2: a major update that brings first-class concurrency support and more expressive APIs for a seamless developer experience. Inconsistent and poorly documented service APIs create integration headaches for developers. gRPC is a modern, high-performance framework for building service APIs, enabling efficient communication between systems over a network. Since services may be written with a different language than their clients, most gRPC services use Protocol Buffers (or “protobufs”) to define their APIs and the messages exchanged between clients and servers. Service contracts are defined in a neutral, cross-platform format using `.proto` files. This is the foundation of your service, not an artefact of its implementation. And thanks to the format’s efficient binary serialization, these messages are typically smaller and faster to process than other standard formats like JSON. gRPC Swift is one of a family of similar tools that use the Protocol Buffers contract to generate code in the language you’re working with, making it easy to build clients and servers that adhere to your service contract. And the new gRPC Swift 2 offers an idiomatic, cross-platform, performant and feature-rich library for building highly-scalable services. This release is a major update that takes advantage of many modern Swift features for cross-platform services development. When gRPC Swift was first developed back in 2018, Swift had not yet introduced concurrency features like async/await, so it was instead based on SwiftNIO’s event-driven concurrency model. For developers unfamiliar with these concepts, the prior version of gRPC Swift presented a steep learning curve. Now that Swift’s modern concurrency model is fully established, we seized the opportunity to rethink gRPC Swift for today’s Swift, incorporating lessons learned from our years of use at Apple for building internet-scale services. ## Highlights * Modern, flexible, and easy-to-use APIs with idiomatic generated code. * Full support for building services and clients on Linux and Apple platforms. * Pluggable transports including a high-performance HTTP/2 transport built on top of SwiftNIO, and an in-process transport which is great for testing. * Smart client features like client-side load balancing, a pluggable name resolution mechanism and automatic retries. * A flexible interceptor layer allowing you to implement cross-cutting logic like authentication, logging, and metrics. ## Hello, swift.org! Consider the canonical “hello world” service with a single API which returns a greeting. You might define it like this in a `.proto` file: syntax = "proto3"; service GreetingService { // Returns a personalized greeting. rpc SayHello(SayHelloRequest) returns (SayHelloResponse); } message SayHelloRequest { // The name of the person to greet. string name = 1; } message SayHelloResponse { // The personalized greeting message. string message = 1; } gRPC can be configured to generate: * Service code so you can implement the business logic. * Client code to make requests against the service. Code for messages is generated by SwiftProtobuf and used in conjunction with the generated gRPC code. ### Generated Service Code The generated code includes a Swift protocol describing the requirements of the service with one method for each `rpc` in the service definition. To implement the business logic of your service just implement one of the service protocols. The example below uses the `SimpleServiceProtocol` which is the highest level API. If you need more flexibility you can use the `ServiceProtocol` or `StreamingServiceProtocol` which trade off conciseness for flexibility. To start the service you need to create a server configured to use a transport and an instance of your service: import GRPCCore import GRPCNIOTransportHTTP2 struct Greeter: GreetingService.SimpleServiceProtocol { func sayHello( request: SayHelloRequest, context: ServerContext ) async throws -> SayHelloResponse { return SayHelloResponse.with { $0.message = "Hello, \(request.name)!" } } } @main struct GreeterServer { static func main() async throws { // Create a plaintext server using the SwiftNIO based HTTP/2 transport // listening on 128.0.0.1:8080. let server = GRPCServer( transport: .http2NIOPosix( address: .ipv4(host: "127.0.0.1", port: 8080), transportSecurity: .plaintext ), services: [Greeter()] ) // Start serving indefinitely. try await server.serve() } } ### Generated Client Code gRPC generates an idiomatic client for you, simplifying service calls. To use it, first create a raw client and wrap it with the generated client specific to your service. This generated client provides a type-safe way for you to easily interact with your service. import GRPCCore import GRPCNIOTransportHTTP2 @main struct SayHello { static func main() async throws { // Create a plaintext client using the SwiftNIO based HTTP/2 transport // connecting to a service listening on 128.0.0.1:8080. try await withGRPCClient( transport: .http2NIOPosix( target: .dns(host: "127.0.0.1", port: 8080), transportSecurity: .plaintext ) ) { client in let greeter = GreetingService.Client(wrapping: client) let greeting = try await greeter.sayHello(.with { $0.name = "swift.org" }) print(greeting.message) } } } ## Package Ecosystem gRPC Swift 2 was designed with flexibility in mind. It’s distributed as a collection of packages, allowing you to pick and choose the components which best suit your needs. These features are provided by the following packages: * grpc/grpc-swift-2 provides runtime abstractions and types. * grpc/grpc-swift-nio-transport implements client and server transports using HTTP/2 and is built on top of SwiftNIO. * grpc/grpc-swift-protobuf integrates with SwiftProtobuf to provide a code generator for services defined in `.proto` files. * grpc/grpc-swift-extras includes common gRPC add-ons, like the reflection and health services, integrations with Swift Service Lifecycle, and interceptors to trace RPCs using OpenTelemetry. ## Next Steps To get started with gRPC Swift 2 check out the tutorials and documentation which are hosted on the Swift Package Index, or try out one of the examples in the grpc/grpc-swift-2 repository. If you have feature requests, want to report a bug, or would like to contribute to the project then please reach out to us on GitHub or join us on the Swift forums. Let’s connect!
06.08.2025 18:10 — 👍 0    🔁 0    💬 0    📌 0
Updating the Visual Studio Code extension for Swift Today, we are excited to announce a new version of the Swift extension for Visual Studio Code – now published to the extension marketplace as an official supported release of the Swift team. The aim of this extension is to provide a high-quality, feature-complete extension that makes developing Swift applications on all platforms a seamless experience. As we continue to invest in Swift as a first-class language for cross-platform development, both Apple and the broader developer community are rapidly iterating on the VS Code extension to expand its capabilities for server and cloud, embedded, and Linux and Windows app development. The original extension was developed by members of the Swift Server Working Group, and with its broader scope, they have graciously supported this transition to the GitHub /swiftlang organization and the creation of a new publisher for the extension. For existing Swift developers using VS Code, the transition should be seamless: the old release should automatically install the new extension and disable itself, and moving forward all language features will be provided by the new extension. You’re welcome to uninstall the original extension, which has been renamed to reflect its deprecated status. Further details about the migration can be found on the Swift Forums. If you have any issues migrating, please file an issue or comment on the forum post.
06.08.2025 18:10 — 👍 0    🔁 0    💬 0    📌 0
Introducing swiftly 1.0 Today we’re delighted to introduce the first stable release of swiftly, a Swift version manager that takes the pain out of installing, managing and updating your Swift toolchain. The latest version of Swift is bundled with Xcode for writing apps for Apple platforms. But perhaps you want to install Swift on a different platform like Linux, or use a different version of the toolchain for building services or command line tools. Downloading, extracting and installing a trusted build of Swift along with the relevant dependencies for your operating system can require quite a few manual and error-prone steps. swiftly has been around for some years as a community-supported tool for Swift developers using Linux. With this release, we’re officially supporting it as part of the core Swift toolchain, including hosting it as part of the Swift GitHub organization. We’ve also added macOS support to make it easier to install Swift separately from Xcode. ## Introducing swiftly swiftly is the best tool to install the standalone toolchain, providing commands to install Swift on a new system, update to the latest stable version, and experiment or test with nightly snapshots or older versions. It also makes it easy to switch effortlessly between multiple installed toolchains. You can even add a file to your project repository so swiftly will use the same toolchain version for all members of your development team. Naturally, swiftly itself is written in Swift, and is able to update itself to the latest version. ## Quick tour Let’s take a look at some of the features of swiftly! To get started, visit swift.org/install and install it. swiftly will provide directions after installation if there are any system packages, or shell commands needed for smooth operation of the new toolchain. The latest Swift toolchain is installed as the default, so you can immediately use it to start a new project. For example: $ swift package init The `swiftly use` command selects the default toolchain for Swift commands (e.g. `swift test`, `swift build`): $ swiftly use 6.0.3 $ swift --version -- Apple Swift version 6.0.3 (swiftlang-6.0.3.1.2 clang-1600.0.28.6) Target: arm64-apple-macosx15.0 At a later point, if there’s a new release of Swift you can install it alongside the existing toolchain with the `latest` command: $ swiftly install latest Pre-release of versions of Swift are available, including nightly “snapshot” toolchains. They can be easily listed using swiftly: $ swiftly list-available main-snapshot -- Available main development snapshot toolchains ---------------------------------------------- main-snapshot-2025-03-25 ... Once you’ve identified a snapshot toolchain, it can be installed using its name: $ swiftly install main-snapshot-2025-03-25 -- Installing main-snapshot-2025-03-25 Another way to temporarily use a specific version of Swift is to use the special ‘+’ selector. With this syntax, you don’t need to first switch to a different toolchain: $ swiftly run lldb +main-snapshot-2025-03-25 -- (lldb) _ If you’re building a SwiftPM project in a team setting and want to enforce a common version of the Swift toolchain on all contributors, simply create a `.swift-version` file in the root of your project folder with the desired version (e.g. “6.0.3”). As swiftly is updated with new features and bug fixes, you can run `swiftly self-update` to check and install new releases. ## How swiftly works By writing swiftly in Swift, we’re able to take advantage of the language’s features, support, and ecosystem of related projects. Swift comes with standard library features for working with the filesystem in its Foundation module. For network operations Async HTTP Client is there to work the HTTP requests. And to retrieve the latest Swift release, swiftly uses the Swift OpenAPI plugin to generate the code to interact with the swift.org website. Lastly, it takes advantage of Swift’s interoperability with C to use the existing libarchive library to work with archives. swiftly uses libarchive to extract the toolchains downloaded from the Swift website and the integration is simple. It can be challenging to build shell programs that work well across multiple platforms with minimal system dependencies; this motivated us to switch swiftly away from using a shell program to install it and become a self-installing binary application. swiftly has access to excellent argument parsing capabilities, beautiful `--help` screens, and the full standard library. The only remaining problem was being able to deliver the operating system and processor architecture specific binary to the users system with simplicity. The swift.org website helps with operating system detection, but it cannot reliably detect the Linux distribution. Luckily, there is the Swift Static Linux SDK that makes binaries that work with a wide range of distributions. The processor architecture can be determined on most unixes using `uname -m` . The result of all of this is the simplicity of a copy and paste from the website to your terminal and get started with Swift. ## Installing Swift, swiftly Moving forward, swiftly will become the default way to install Swift outside of Xcode. The initial version supports macOS and a variety of Linux distributions, including Ubuntu, Debian, Fedora, Red Hat Enterprise Linux and Amazon Linux. The swiftly documentation provides further information about using swiftly in a CI/CD environment, as well as setting proxy servers and custom install locations for enterprise environments. swiftly is an open source project, and so you can raise new issues or contribute pull requests at its GitHub repository. You can also ask questions or discuss swiftly on the Swift Forums. Special thanks to Patrick Freed for creating swiftly, contributing it to the Swift organization, and his continued contributions to this valuable tool. The community is what makes Swift amazing!
06.08.2025 18:10 — 👍 0    🔁 0    💬 0    📌 0
Swift 6.1 Released Swift 6.1 is now available! This release includes new language enhancements to improve productivity, diagnostics improvements, package traits, and ongoing work to improve data-race safety usability and compile times. Read on for an overview of the changes to the language, package manager, and next steps for getting started with Swift 6.1. ## Language and Standard Library ### Concurrency Swift’s concurrency model allows writing `nonisolated` on properties and functions to indicate that an API is safe to call from any concurrent context. Swift 6.1 extends `nonisolated` to types and extensions. This allows you to write `nonisolated` to prevent `@MainActor` inference on a type, or to apply `nonisolated` to all methods in an extension without having to annotate every method: @MainActor struct S { let id: Int let name: String // mutable state and MainActor methods } nonisolated extension S: CustomStringConvertible, Equatable { var description: String { "id: \(id), name: \(name)" } static func ==(lhs: S, rhs: S) -> Bool { lhs.id == rhs.id } } Swift 6.1 also improves type inference for task groups by inferring the child task result type of `withTaskGroup` and `withThrowingTaskGroup`. Previously, you always had to write the child task result type as an argument when creating the task group: let messages = await withTaskGroup(of: Message.self) { group in for id in ids { group.addTask { await downloadMessage(for: id) } } var messages: [Message] = [] for await message in group { messages.append(message) } return messages } In Swift 6.1, the child task result type can be inferred from the task group closure: // No need for `(of: Message.self)` like before. let messages = await withTaskGroup { group in for id in ids { group.addTask { await downloadMessage(for: id) } } var messages: [Message] = [] for await message in group { messages.append(message) } return messages } The approachability of data-race safety remains an area of active development; you can find an overview of the approach in the vision document for improving the approachability of data-race safety. Many Swift Evolution proposals implementing the features described in the vision document are under active review, and your feedback will help shape these improvements. ### Implementing Objective-C types in Swift Swift 6.1 includes a new attribute, `@implementation`, which can be used together with `@objc` to provide an implementation for a declaration that has been imported from Objective-C. You can write `@objc @implementation` on a Swift `extension` to replace an Objective-C `@implementation` block. You write headers as normal for an Objective-C class, but instead of writing an `@implementation` in an Objective-C file, you write an `@objc @implementation extension` in a Swift file. You can even port an existing class’s implementation to Swift one category at a time without breaking backwards compatibility. ### Productivity enhancements Swift allows including trailing commas in collection literals to make it easy to append, remove, reorder, or comment out the last element as any other element: let rank = [ "Player 1", "Player 3", "Player 2", ] Swift 6.1 extends trailing comma support to tuples, parameter and argument lists, generic parameter lists, closure capture lists, and string interpolations: let numbers = [1, 2, 0, 3, 4, 0, 0, 5] let subsequences = numbers.split( separator: 0, maxSplits: 1, ) In addition to improved development ergonomics, code generation tools like plugins and macros can be simplified, because generating a comma-separated list no longer needs a special condition for the last element. You can find a complete list of language proposals that were accepted through the Swift Evolution process and implemented in Swift 6 on the Swift Evolution dashboard. ## Package and build improvements Swift 6.1 introduces _package traits_ , a new configuration for packages that allows them to offer different APIs and features when used in specific environments, such as Embedded Swift and WebAssembly. Package authors can define a set of traits in their `Package.swift` that their package offers, which provide a way to express conditional compilation and optional dependencies. The package can specify a set of default traits that are enabled in clients, and clients can customize the traits they use when they declare the dependency: dependencies: [ .package( url: "https://github.com/Org/SomePackage.git", from: "1.0.0", traits: [ .default, // enable all of the package's default traits "Embedded" ] ), ] Many editing features, such as jump to definition for APIs in libraries you’re using, are powered by indexing. Before Swift 6.1, indexing occurred when you built your project, which meant that any additions or changes to the library were only surfaced by those editing features after you perform a build. Swift 6.1 enables background indexing by default for SwiftPM projects in SourceKit-LSP. Cross-module and global functionality stays updated as you make changes to your project. ## Swift Testing Swift 6.1 enables custom Swift Testing traits to perform logic before or after tests run in order to share set-up or tear-down logic. If you write a custom trait type which conforms to the new `TestScoping` protocol, you can implement a method to customize the scope in which each test or suite the trait is applied to will execute. For example, you could implement a trait which binds a task local value to a mocked resource: struct MockAPICredentialsTrait: TestTrait, TestScoping { func provideScope(for test: Test, testCase: Test.Case?, performing function: @Sendable () async throws -> Void) async throws { let mockCredentials = APICredentials(apiKey: "fake") try await APICredentials.$current.withValue(mockCredentials) { try await function() } } } extension Trait where Self == MockAPICredentialsTrait { static var mockAPICredentials: Self { Self() } } @Test(.mockAPICredentials) func example() { // Validate API usage, referencing `APICredentials.current`... } For more details, see ST-0007: Test Scoping Traits. Swift Testing in Swift 6.1 also includes refined versions of the `#expect(throws:)` and `#require(throws:)` macros which return their caught errors, making inspecting them in test functions more ergonomic (ST-0006). ## Swift-DocC Swift-DocC introduces a more human readable and human writable alternative for symbol link disambiguation based on parameter type and return type information. For example, consider these three function overloads with different parameter types and return types: func doSomething(first: String, second: Int) -> Double func doSomething(first: String?, second: Int) -> Float func doSomething(first: String?, second: Int) -> Double Previously, if you wrote a link to one of these overloads you needed to include a short hash of that symbol’s unique identifier to disambiguate the link and uniquely reference the specific overload. Swift-DocC’s warnings aided in writing these hashes but a person can’t decode the resulting hash suffix (`-3c5j`) to determine which overload the link is referring to. Now, you can use a combination of parameter types and return types—like `-(String,_)`, `->Float,` or `-(String?,_)->Double`—to disambiguate the link and uniquely reference a specific overload. You can discover the minimal combination of parameter types and return types for each overload from Swift-DocC’s warnings about ambiguous symbol links. For more details, see the Ambiguous Symbol Links section of Linking to Symbols and Other Content. ## Install Swift 6.1 You can try out these exciting new developments in Swift 6.1 today! If you’re building apps for Apple platforms, Swift 6.1 is included in Xcode 16.3, now available from the App Store. And the easiest way to install the standalone Swift 6.1 toolchain is using swiftly, the new Swift version manager that runs on macOS and Linux. Additional installation methods, including for Windows, are included on the Install Swift page.
06.08.2025 18:10 — 👍 0    🔁 0    💬 0    📌 0
Swift at Apple: Migrating the Password Monitoring service from Java _Swift is heavily used in production for building cloud services at Apple, with incredible results. Last year, the Password Monitoring service was rewritten in Swift, handling multiple billions of requests per day from devices all over the world. In comparison with the previous Java service, the updated backend delivers a 40% increase in performance, along with improved scalability, security, and availability._ The Passwords app, introduced in the fall of 2024, helps users manage their passwords, passkeys, and verification codes. It allows them to store, autofill, and generate strong passwords that can be shared across all their devices, as well as share passwords with trusted contacts. One security feature included in the app is Password Monitoring, which warns users if one of their saved passwords shows up in a data leak. This feature has a server component, running on Linux-based infrastructure, that is maintained by Apple. On a regular interval, Password Monitoring checks a user’s passwords against a continuously updated and curated list of passwords that are known to have been exposed in a leak. Importantly, this task is handled in a thoughtful, privacy-preserving way that never reveals users’ passwords to Apple. A detailed discussion of how this is done using the cryptographic private set intersection protocol is in the Password Monitoring section of the Apple Platform Security guide. The migration from Java to Swift was motivated by a need to scale the Password Monitoring service in a performant way. The layered encryption module used by Password Monitoring requires a significant amount of computation for each request, yet the overall service needs to respond quickly even when under high load. ## Choosing Swift for increased performance For years, our team relied on Java to power large-scale, mission-critical services because of its proven stability and performance. However, Java’s memory management approach no longer aligns with our growing demands and efficiency goals. Instead of simply expanding hardware resources, we were seeking a more-efficient language to support our growth while reducing server overhead. Prior to seeking a replacement language, we sought ways of tuning the JVM to achieve the performance required. Java’s G1 Garbage Collector (GC) mitigated some limitations of earlier collectors by introducing features like predictable pause times, region-based collection, and concurrent processing. However, even with these advancements, managing garbage collection at scale remains a challenge due to issues like prolonged GC pauses under high loads, increased performance overhead, and the complexity of fine-tuning for diverse workloads. One of the challenges faced by our Java service was its inability to quickly provision and decommission instances due to the overhead of the JVM. The Password Monitoring service runs globally, so service load can greatly fluctuate throughout the day, even with client-side techniques to smooth over the distribution of traffic. The peak and trough of a day differ by approximately 50% regionally. To efficiently manage this, we aim to scale down when demand is low and scale up as demand peaks in different regions. A faster bootstrap time is a crucial requirement to support this dynamic scaling strategy. Given the scale of our application and the volume of traffic we manage daily, the decision to transition from Java to another language was not made lightly. We evaluated our options, and found only a few languages that could help us achieve our goals. While you might expect that Apple would automatically choose Swift, we were pleasantly surprised by how well it fit the unique needs of a cloud-based service like ours. Swift has expressive syntax that was easy to learn, and could deliver the performance improvements necessary to meet the demands of our compute workloads. We decided to take a significant leap and started a rewrite of the Password Monitoring backend using Swift. ## Our experience developing with Swift We began rewriting our service using Vapor, a Swift web framework that provided Routing, Controller, and Content modules that we were able to build upon. Our service had additional requirements that led us to create a few custom packages with essential functionality: elliptic curve operations that are crucial for implementing password monitoring, auditing, configuration, error handling, and custom middleware. One of the most significant aspects of Swift that impressed us was its emphasis on protocols. In Java, we relied heavily on inheritance, which can lead to complex class hierarchies and tight coupling. Swift’s approach of protocols and generics promotes modularity and reusability by allowing classes, structs, and enums to share common protocols, enabling a more flexible and scalable codebase. This shift in mindset encouraged us to think in terms of behaviors rather than concrete classes, resulting in cleaner and more maintainable code. Safety is another area where Swift takes a distinctive approach compared to Java. For example, Swift’s optional type and safe unwrapping mechanisms eliminate the need for null checks everywhere, reducing the risk of null pointer exceptions and enhancing code readability. This safety-first approach ingrained throughout Swift’s language design, whether it is deterministic deallocation, copy-on-write (CoW), or value types, makes it inherently less prone to runtime errors. Swift’s async/await support is a nice addition, streamlining how we handle async tasks. Previously, managing async operations often involved complex callback patterns or external libraries. Swift’s async/await syntax simplifies this process, making it more intuitive and less error-prone. We can now write async code that reads like sync code, leading to more readable, testable, and maintainable concurrency handling—especially critical in high-load, multi-threaded environments. Overall, our experience with Swift has been overwhelmingly positive and we were able to finish the rewrite much faster than initially estimated. Swift allowed us to write smaller, less verbose, and more expressive codebases (close to 85% reduction in lines of code) that are highly readable while prioritizing safety and efficiency. Our service benefited from a diverse ecosystem of Swift packages, including logging frameworks, a Cassandra client, and crypto libraries that were readily available. In addition to an excellent support system and tooling, Swift’s inherent emphasis on modularity and extensibility helped future-proof and simplify the integration and customizations needed for our service-specific functions. ## Takeaways for future Swift on server development We benchmarked performance throughout the process of development and deployment, allowing us to discover the trait of the Swift programming language that delighted us the most — its efficiency. Swift’s deterministic memory management led to a much lower memory threshold for our service. Not only were our initial results heartening, but after a few iterations of performance improvements, we had close to 40% throughput gain with latencies under 1 ms for 99.9% of requests on our current production hardware. Additionally, the new service had a much smaller memory footprint per instance — in the 100s of megabytes — an order of magnitude smaller compared to the 10s of gigabytes our Java implementation needed under peak load to sustain the same throughput and latencies. The service runs on Kubernetes, and the migration’s efficiency improvements allowed us to release about 50% of its capacity for other workloads. Our Swift implementation has run smoothly and efficiently in production, making it worth the effort we put into this migration. In addition to outperforming our previous Java-based application, Swift delivered better performance consistency, enhanced safety features, and robust reliability — all while requiring fewer resources by utilizing memory and CPU efficiently. With fewer lines of boilerplate code and more flexible design patterns that we used, we look forward to simplified maintenance of our application. Swift was a powerful choice for building fast, resilient, and maintainable applications in our high-demand environment.
06.08.2025 18:10 — 👍 0    🔁 0    💬 0    📌 0
Redesigned Swift.org is now live Over the past few months, the website workgroup has been redesigning Swift.org. On behalf of the website workgroup, I’m pleased to announce that we have merged the initial changes. Our goal with the site redesign has been to make Swift.org more approachable for newcomers to Swift, highlight the language’s technical strengths, and make it easy to get started. That led to a focus on the website’s appearance, improving the user experience, and emphasizing important features such as Swift’s multiplatform support. Today’s release includes refreshed home and install pages. Additionally, new pages have been designed to explore Swift use cases, including cloud services, command line tools, and embedded software. Looking forward, we plan to take an iterative approach to improving the website, including pushing changes live as we complete their design and implementation. ## Brand new design We explored several design options and found that the latest design conveys the fluidity and creativity of Swift through the splash of orange and the bird animation in the background. ## Curated content and examples The homepage now highlights Swift’s strengths alongside code examples that illustrate them. Additionally, we showcase various types of software that can be developed using Swift; these new use case pages provide information such as relevant packages, examples of Swift in action, code snippets, and links to resources for further learning. ## Next Steps We look forward to hearing your feedback on this first set of changes as we continue to redesign other sections of the site. There are several ways to offer feedback on the redesign and to get involved: * A forum announcement has been shared on the forums that can be used for discussion, and the website repository has GitHub issues. * The website itself is open source, and your contributions to the swiftlang/swift-org-website repository are welcome. * The Swift Information Architecture Project is an ongoing effort that has helped inform decisions related to the site redesign. Thank you to the website workgroup and community members for contributing to these improvements.
06.08.2025 18:10 — 👍 0    🔁 0    💬 0    📌 0
Announcing Swift 6 We’re delighted to announce the general availability of Swift 6. This is a major new release that expands Swift to more platforms and domains. Many people know of Swift as a language for app development, with a million apps on the App Store. But Swift is great for more than just apps. Swift’s safety, speed, and approachability make it a great choice for many other use cases including libraries, internet-scale services, and the most performance-critical and secure code. Swift 6 scales even further through new low-level programming features, an embedded Swift language subset, expanded Linux and Windows support, new cross-platform APIs including the new Swift Testing library, and more. Read on for a deep dive into changes to the language, standard libraries, debugging, platform support, and next steps for getting started with Swift 6. ## Language and Standard Library ### Concurrency Swift has long offered memory safety, ensuring that variables are initialized before they’re used, memory isn’t accessed after it’s been deallocated, and array indices are checked for out-of-bounds errors. Swift 6 now includes a new, opt-in language mode that extends Swift’s safety guarantees to prevent data races in concurrent code by diagnosing potential data races in your code as compiler errors. Data-race safety checks were previously available as warnings in Swift 5.10 through the `-strict-concurrency=complete` compiler flag. Thanks to improved `Sendable` inference and new compiler analysis for transferring mutable state from one actor to another, Swift 6 warnings about data-race safety have fewer false positives. You can find more information about the Swift 6 language mode and how to migrate at Swift.org/migration. Swift 6 marks the start of the journey to make data-race safety dramatically easier. The usability of data-race safety remains an area of active development, and your feedback will help shape future improvements. Swift 6 also comes with a new Synchronization library for low-level concurrency APIs, including atomic operations and a new mutex API. ### Typed throws Swift 6 enables functions to specify the type of error that they throw as part of their signature. This feature is useful in generic code that forwards along errors thrown in client code, or in resource-constrained environments that cannot allocate memory, such as in embedded Swift code. For example: func parseRecord(from string: String) throws(ParseError) -> Record { // ... } A call to `parseRecord(from:)` will either return a `Record` instance or throw an error of type `ParseError`. A `do..catch` block will infer `ParseError` as the type of the `error` variable: do { let record = try parseRecord(from: myString) } catch { // 'error' has type 'ParseError' } Typed throws generalizes over throwing and non-throwing functions. A function that is specified as `throws` (without a specific error type) is equivalent to one that specifies `throws(any Error)`, whereas a non-throwing function is equivalent to one that specifies `throws(Never)`. Calls to functions that are `throws(Never)` are non-throwing and don’t require error handling at the call site. Typed throws can also be used in generic functions to propagate error types from parameters, in a manner that is more precise than `rethrows`. For example, the `Sequence.map` method can propagate the thrown error type from its closure parameter, indicating that it only throws the same type of errors as the closure: extension Sequence { func map<T, E>(_ body: (Element) throws(E) -> T) throws(E) -> [T] { // ... } } When given a closure that throws `ParseError`, `map` will throw `ParseError`. When given a non-throwing closure, `E` is inferred to `Never` and `map` will not throw. ### Ownership Swift 5.9 introduced non-copyable types with the `~Copyable` syntax for modeling resources with unique ownership, and writing performance-conscious code by eliminating the runtime overhead associated with copying. Swift 6 now supports these types with the generics system, making it possible to write generic code that works with both copyable and non-copyable types. For example: protocol Drinkable: ~Copyable { consuming func use() } struct Coffee: Drinkable, ~Copyable { /* ... */ } struct Water: Drinkable { /* ... */ } func drink(item: consuming some Drinkable & ~Copyable) { item.use() } drink(item: Coffee()) drink(item: Water()) The `Drinkable` protocol has no requirement that its conforming types are `Copyable`. This means both the non-copyable type `Coffee` and copyable type `Water` can be passed into the generic `drink` function. Switch statements can now be written to avoid copying within enum pattern-matching operations. This means that switch statements can be used with non-copyable payloads and can also provide performance benefits for copyable payloads, especially those based on copy-on-write containers like `Array` and `Dictionary`. Non-copyable types are already used throughout the standard libraries. For instance, the new `Atomic` type in the Synchronization library is based on `~Copyable`, `Optional` and `Result` can now wrap non-copyable types, and the unsafe buffer pointer types can now point to non-copyable elements. C++ interoperability also uses non-copyable types to expose C++ move-only types to Swift. ### C++ interoperability Swift 5.9 introduced bidirectional interoperability with C++ to seamlessly bring Swift to more existing projects. Swift 6 expands interoperability support to C++ move-only types, virtual methods, default arguments, and more standard library types including `std::map` and `std::optional`. C++ types that do not have a copy constructor can now be accessed from Swift 6 as non-copyable types with `~Copyable`. And for those times when it’s useful to expose a C++ type with a copy constructor as `~Copyable` in Swift for better performance, a new `SWIFT_NONCOPYABLE` annotation can be applied to the C++ type. Swift now also supports calls of C++ virtual methods on types annotated as `SWIFT_SHARED_REFERENCE` or `SWIFT_IMMORTAL_REFERENCE`. When calling C++ functions or methods that have default argument values for some of their parameters, Swift now respects these default values, rather than requiring you to explicitly pass an argument. ### Embedded Swift Swift 6 includes a preview of Embedded Swift, a language subset and compilation mode suitable for embedded software development, such as programming microcontrollers. The toolchain supports ARM and RISC-V bare-metal targets. Embedded Swift produces small and standalone binaries by relying on generic specialization. Since it doesn’t rely on a runtime or type metadata, Embedded Swift is suitable for platforms with tight memory constraints as well as use in low-level environments with limited runtime dependencies. Embedded Swift remains an experimental feature, with ongoing development before stable support in a future Swift release. ### 128-bit Integers Swift 6 rounds out the set of low-level integer primitives with the addition of signed and unsigned 128-bit integer types. These are available on all Swift platforms, and provide the same API as other fixed-width integer types in the standard library. ### Productivity enhancements Swift 6 introduces a number of productivity enhancements, including `count(where:)` to streamline counting the number of elements in a sequence that satisfy a predicate, pack iteration for writing natural `for`-loops over the elements in a value parameter pack, access control for imports to keep implementation details from leaking into your public APIs, `@attached(body)` macros for synthesizing and augmenting function implementations, expression macros as default arguments, and more. You can find a complete list of language proposals that were accepted through the Swift Evolution process and implemented in Swift 6 on the Swift Evolution dashboard. ## Debugging ### Custom LLDB summaries with `@DebugDescription` @DebugDescription` section" href="#custom-lldb-summaries-with-debugdescription"> Swift 6 provides a new debugging macro to easily customize how an object is displayed in LLDB when using the `p` command, and in the variables view in Xcode and VSCode, by using a formatting scheme that does not run arbitrary code. Types that conform to `CustomDebugStringConvertible` provide a `debugDescription` property that returns a string describing the object. In LLDB, the `po` command calls this computed property on an object. In contrast, the `p` command uses LLDB’s type summary formatters to directly format the object using its stored property values. `@DebugDescription` is a new macro in the standard library which lets you specify LLDB type summaries for your own types directly in code. The macro processes the `debugDescription` property, translating simple string interpolations involving stored properties into LLDB type summaries. This allows LLDB to use your custom formatting even when using `p`, and also in Xcode or VSCode’s variable display windows. The macro can use an existing conformance to `CustomDebugStringConvertible`, or you can provide a separate string interpolation only for use in LLDB’s `p` command. Providing a separate LLDB description string is useful if your `CustomDebugStringConvertible` implementation doesn’t meet the requirements of the `@DebugDescription` macro, or if you’re familiar with the LLDB Summary String syntax and you want to use it directly. For example, the following code customizes how `po` in LLDB displays the `Organization` type with a conformance to `CustomDebugStringConvertible`, and the `@DebugDescription` macro exposes this custom formatting to the `p` command and the variables view: @DebugDescription struct Organization: CustomDebugStringConvertible { var id: String var name: String var manager: Person // ... and more var debugDescription: String { "#\(id) \(name) [\(manager.name)]" } } (lldb) p myOrg (Organization) myOrg = "`#100 Worldwide Travel [Jonathan Swift]`" ### Improved startup performance with explicit modules Swift 6 dramatically improves startup performance in the debugger when you use explicit module builds. When debugging locally-built code, LLDB can now import explicitly-built Swift and Clang modules directly from the project build artifacts. This avoids the need to recompile implicit Clang module dependencies from source, which can take a long time, and it’s very sensitive to issues with header search paths. If the first `p` or `po` command in LLDB takes a long time due to Clang module compilation, or if your debugging is frequently blocked by Clang header import problems, consider adopting explicit modules in your project! ## Libraries ### Foundation Swift 6 unifies the implementation of Foundation across all platforms. The modern, portable Swift implementation provides consistency across platforms, it’s more robust, and it’s open source. macOS and iOS started using the Swift implementation of Foundation alongside Swift 5.9, and Swift 6 brings these improvements to Linux and Windows. Core types like `JSONDecoder`, `URL`, `Calendar`, `FileManager`, `ProcessInfo`, and more have been completely reimplemented in Swift. These types share their implementation with macOS 15 and iOS 18, providing a new level of cross-platform consistency, reliability, and performance. Recently released APIs like `FormatStyle`, `ParseStrategy`, `Predicate`, and `JSON5`, from past macOS and iOS releases are now available on all Swift platforms. New Foundation APIs like `Expression`, calendar enumeration improvements, calendar recurrence rules, format style enhancements, and more are available simultaneously on macOS, iOS, Linux, and Windows - and they were built with community involvement. If your Linux or Windows app imports the `Foundation` library from the Swift toolchain today, you get all of these improvements for free. And if your app is particularly sensitive to binary size, you can now import the `FoundationEssentials` library, which provides a more targeted subset of Foundation’s features that omits internationalization and localization data. ### Swift Testing Swift 6 introduces Swift Testing, a new testing library designed from the ground up for Swift. It includes expressive APIs that make it easy to write and organize tests. It provides detailed output when a test fails using macros like `#expect`. And it scales to large codebases with features like parameterization to easily repeat a test with different arguments. For example: @Test("Continents mentioned in videos", arguments: [ "A Beach", "By the Lake", "Camping in the Woods" ]) func mentionedContinents(videoName: String) async throws { let videoLibrary = try await VideoLibrary() let video = try #require(await videoLibrary.video(named: videoName)) #expect(video.mentionedContinents.count <= 3) } Swift Testing takes full advantage of macros. Its `@Test` and `@Suite` attached macros declare test functions and suite types respectively, and they accept arguments (known as traits) to customize various behaviors. The `#expect` and `#require` expression macros validate expected behaviors, and capture rich representation of expressions and their sub-values to produce detailed failure messages. Since Swift Testing is included directly in Swift 6 toolchains, you can `import Testing` without needing to declare a package dependency. This means your tests do not need to build Swift Testing or its dependencies (including swift-syntax), and its macro implementation comes prebuilt. The package manager in Swift 6 automatically builds and runs Swift Testing tests in addition to XCTests (if present), and shows results from both libraries in log output. Swift Testing supports all platforms that Swift officially supports, including all Apple platforms, Linux, and Windows. To learn more about this new open source project, visit the swift-testing repository on GitHub, and get involved with its ongoing development on the forums. ## Platform Support Swift is designed to support development and execution on all major operating systems, and platform consistency and expansion underpins Swift’s ability to reach new programming domains. Swift 6 brings major improvements to Linux and Windows across the board, including support for more Linux distributions and Windows architectures. Toolchains for all of the following platforms are available for download from Swift.org/install. ### Fully static SDK for Linux Swift 6 supports building fully statically linked executables for Linux; these have no external dependencies, so they are ideal for situations where you want to copy a program directly onto a system or into a container and run it without installing any extra software. The SDK can also be used to cross-compile to Linux from other platforms. Learn how to get started with the static SDK for Linux on Swift.org. ### New Linux distributions Swift 6 adds official support and testing for Debian and Fedora, as well as on Ubuntu 24.04. ### Windows build performance Prebuilt toolchains are now available for the arm64 architecture, which provides improved compiler performance for Windows on ARM hosts. In Swift 6, the Swift package manager also parallelizes builds across multiple cores on Windows by default. On a 10-core machine, this can improve build performance by up to a factor of 10! ## Next Steps ### Download Swift 6 You can try out these exciting new developments in Swift 6 today! Install the official Swift 6 toolchains for macOS, Linux, and Windows at Swift.org/install. ### Get started with Swift The Swift Programming Language book has been updated to reflect the latest Swift 6 syntax and features. It serves as the official Swift guide and an excellent starting point for learning the language. To help kickstart your Swift journey, Swift.org/getting-started offers tutorials for various use cases, including building a cross-platform library, a web service using Vapor, and an embedded application for a microcontroller. There are also articles for diving deeper into some of Swift’s most popular features. ### Explore the package ecosystem The Swift package ecosystem is continuously growing with new technologies to help you with a variety of tasks in your projects. You can explore package highlights at Swift.org/packages, which features popular package categories and a selection of new and notable packages that are hand-curated from an open nomination process every month. ### Get involved Your experience with Swift 6 and your feedback can help shape the future evolution of the language, the tools, the package ecosystem, and the community. You can get involved by sharing your packages, documentation improvements, educational content, bug reports and enhancement requests, code contributions, and participating in forum discussions. Learn more at Swift.org/contributing. Swift 6 is the culmination of countless contributions from members across the Swift community, and it marks a decade of building this incredible language, ecosystem, and community together. Thank you to everyone who participated in development and provided feedback. Your contributions make Swift a better language.
02.08.2025 12:08 — 👍 0    🔁 0    💬 0    📌 0
The Next Chapter in Swift Build Technologies Swift continues to grow in popularity as a cross-platform language supporting a wide variety of use cases, with support on a variety of embedded devices, form factors that encompass wearables to server, and a wide variety of operating systems. As Swift expands, there’s value in investing in matching cross-platform build tools that provide a powerful, consistent, and flexible experience across the ecosystem. As a foundational step in this new chapter of Swift build technologies, today Apple is open sourcing Swift Build, a powerful and extensible build engine that provides a set of build rules for building Swift projects. Swift Build is the engine used by Xcode, which supports millions of apps in the App Store as well as the internal build process for Apple’s own operating systems. The open source repository also includes support for targeting Linux and Windows. ## Introducing Swift Build The primary responsibility of the build system is to transform user-authored inputs (such as a project description and source code) into output artifacts like command line tools, libraries, and applications. Build systems play an important role in providing a great developer experience, enabling higher level features which determine how users architect and work with their projects. Furthermore, the performance and reliability of a build system has a direct impact on developer productivity. Swift Build is an infrastructural component designed to plan and execute builds requested by a higher-level client like Swift Package Manager or Xcode. It builds on top of the existing llbuild project to add capabilities including: * Robust integration with the Swift compiler to reliably and efficiently coordinate the build of Swift projects * Support for a wide variety of product types including libraries, command line tools, and GUI applications with advanced build configuration options * Build graph optimizations that maximize parallelism when building Swift and C code ## Roadmap for Swift Build Compared to the build engine in Xcode, the build engine in Swift Package Manager is fairly simple. On Apple platforms, having two different ways to build packages has also led to user confusion when the two implementations’ behavior didn’t match. Contributing Xcode’s build engine to the Swift project and developing it in open source alongside the Swift compiler provides the tools necessary to address these problems and deliver a great builds experience to all Swift users. With this release, SwiftPM now has the opportunity to offer a unified build execution engine across all platforms. This change should be transparent to users and maintain full compatibility with all existing packages while delivering a consistent cross-platform experience. At the same time, it lays the foundation to enable new features and improvements across all platforms and tools, and unlocks new performance optimizations and developer-facing features. As a small first step towards this vision, today the team is submitting a pull request to begin the process of integrating support for Swift Build in SwiftPM as an alternate build engine. In the coming months, we’d like to collaborate with the community to complete the work of unifying build system integrations so users can benefit from future tooling improvements across all platforms and project models. We believe this is an important step in continuing to enable a healthy package ecosystem where developers can rely on a consistent, polished development experience — no matter what IDE they’re using or platform they’re targeting. We’ll be sharing more details about this work on the Swift forums, and we’re looking forward to hearing others’ feedback! ## An invitation to participate We look forward to working with the community to continue evolving how we build Swift code. You can find the `swift-build` repository in the Swift organization on GitHub, including a README and documentation describing how to build and contribute. Contributions via pull requests and issues are welcome, and we’d also love to solicit feedback and ideas for improvements on the Swift forum. This is an exciting new chapter for Swift’s build system, and we’re looking forward to all the potential it opens for Swift!
02.08.2025 12:08 — 👍 0    🔁 0    💬 0    📌 0
Introducing gRPC Swift 2 Say hello to gRPC Swift 2: a major update that brings first-class concurrency support and more expressive APIs for a seamless developer experience. Inconsistent and poorly documented service APIs create integration headaches for developers. gRPC is a modern, high-performance framework for building service APIs, enabling efficient communication between systems over a network. Since services may be written with a different language than their clients, most gRPC services use Protocol Buffers (or “protobufs”) to define their APIs and the messages exchanged between clients and servers. Service contracts are defined in a neutral, cross-platform format using `.proto` files. This is the foundation of your service, not an artefact of its implementation. And thanks to the format’s efficient binary serialization, these messages are typically smaller and faster to process than other standard formats like JSON. gRPC Swift is one of a family of similar tools that use the Protocol Buffers contract to generate code in the language you’re working with, making it easy to build clients and servers that adhere to your service contract. And the new gRPC Swift 2 offers an idiomatic, cross-platform, performant and feature-rich library for building highly-scalable services. This release is a major update that takes advantage of many modern Swift features for cross-platform services development. When gRPC Swift was first developed back in 2018, Swift had not yet introduced concurrency features like async/await, so it was instead based on SwiftNIO’s event-driven concurrency model. For developers unfamiliar with these concepts, the prior version of gRPC Swift presented a steep learning curve. Now that Swift’s modern concurrency model is fully established, we seized the opportunity to rethink gRPC Swift for today’s Swift, incorporating lessons learned from our years of use at Apple for building internet-scale services. ## Highlights * Modern, flexible, and easy-to-use APIs with idiomatic generated code. * Full support for building services and clients on Linux and Apple platforms. * Pluggable transports including a high-performance HTTP/2 transport built on top of SwiftNIO, and an in-process transport which is great for testing. * Smart client features like client-side load balancing, a pluggable name resolution mechanism and automatic retries. * A flexible interceptor layer allowing you to implement cross-cutting logic like authentication, logging, and metrics. ## Hello, swift.org! Consider the canonical “hello world” service with a single API which returns a greeting. You might define it like this in a `.proto` file: syntax = "proto3"; service GreetingService { // Returns a personalized greeting. rpc SayHello(SayHelloRequest) returns (SayHelloResponse); } message SayHelloRequest { // The name of the person to greet. string name = 1; } message SayHelloResponse { // The personalized greeting message. string message = 1; } gRPC can be configured to generate: * Service code so you can implement the business logic. * Client code to make requests against the service. Code for messages is generated by SwiftProtobuf and used in conjunction with the generated gRPC code. ### Generated Service Code The generated code includes a Swift protocol describing the requirements of the service with one method for each `rpc` in the service definition. To implement the business logic of your service just implement one of the service protocols. The example below uses the `SimpleServiceProtocol` which is the highest level API. If you need more flexibility you can use the `ServiceProtocol` or `StreamingServiceProtocol` which trade off conciseness for flexibility. To start the service you need to create a server configured to use a transport and an instance of your service: import GRPCCore import GRPCNIOTransportHTTP2 struct Greeter: GreetingService.SimpleServiceProtocol { func sayHello( request: SayHelloRequest, context: ServerContext ) async throws -> SayHelloResponse { return SayHelloResponse.with { $0.message = "Hello, \(request.name)!" } } } @main struct GreeterServer { static func main() async throws { // Create a plaintext server using the SwiftNIO based HTTP/2 transport // listening on 128.0.0.1:8080. let server = GRPCServer( transport: .http2NIOPosix( address: .ipv4(host: "127.0.0.1", port: 8080), transportSecurity: .plaintext ), services: [Greeter()] ) // Start serving indefinitely. try await server.serve() } } ### Generated Client Code gRPC generates an idiomatic client for you, simplifying service calls. To use it, first create a raw client and wrap it with the generated client specific to your service. This generated client provides a type-safe way for you to easily interact with your service. import GRPCCore import GRPCNIOTransportHTTP2 @main struct SayHello { static func main() async throws { // Create a plaintext client using the SwiftNIO based HTTP/2 transport // connecting to a service listening on 128.0.0.1:8080. try await withGRPCClient( transport: .http2NIOPosix( target: .dns(host: "127.0.0.1", port: 8080), transportSecurity: .plaintext ) ) { client in let greeter = GreetingService.Client(wrapping: client) let greeting = try await greeter.sayHello(.with { $0.name = "swift.org" }) print(greeting.message) } } } ## Package Ecosystem gRPC Swift 2 was designed with flexibility in mind. It’s distributed as a collection of packages, allowing you to pick and choose the components which best suit your needs. These features are provided by the following packages: * grpc/grpc-swift-2 provides runtime abstractions and types. * grpc/grpc-swift-nio-transport implements client and server transports using HTTP/2 and is built on top of SwiftNIO. * grpc/grpc-swift-protobuf integrates with SwiftProtobuf to provide a code generator for services defined in `.proto` files. * grpc/grpc-swift-extras includes common gRPC add-ons, like the reflection and health services, integrations with Swift Service Lifecycle, and interceptors to trace RPCs using OpenTelemetry. ## Next Steps To get started with gRPC Swift 2 check out the tutorials and documentation which are hosted on the Swift Package Index, or try out one of the examples in the grpc/grpc-swift-2 repository. If you have feature requests, want to report a bug, or would like to contribute to the project then please reach out to us on GitHub or join us on the Swift forums. Let’s connect!
02.08.2025 12:08 — 👍 1    🔁 0    💬 0    📌 0
How Swift's server support powers Things Cloud You might be familiar with Things, a delightful personal task manager that has won two Apple Design Awards and is available across Apple devices including iPhone, iPad, Mac, Apple Watch, and Apple Vision Pro. At Cultured Code, the team behind Things, we care about a great user experience across every aspect of the product. This extends to our server back end, and after a rewrite our Things Cloud service has transitioned entirely to Swift. Over the past year in production, Swift has consistently proven to be reliable, performant, and remarkably well-suited for our server-side need. Things Cloud serves as the backbone of the app’s experience, silently synchronizing to-dos across devices. The robustness of this work is ensured by a rigorous theoretical foundation, inspired by operational transformations and Git’s internals. After twelve years in production, Things Cloud has earned our users’ trust in its reliability. But despite the enduring strength of the architecture itself, the technology stack lagged behind. Things Cloud synchronizes to-dos across different devices. ## Switching to Swift Our legacy Things Cloud service was built on Python 2 and Google App Engine. While it was stable, it suffered from a growing list of limitations. In particular, slow response times impacted the user experience, high memory usage drove up infrastructure costs, and Python’s lack of static typing made every change risky. For our push notification system to be fast, we even had to develop a custom C-based service. As these issues accumulated and several deprecations loomed, we realized we needed a change. A full rewrite is usually a last resort, but in our case, it was the only viable path for Things Cloud. We explored various programming languages including Java, Python 3, Go, and even C++. However, Swift – which was already a core part of our client apps – stood out for its potential and unique benefits. Swift promised excellent performance, predictable memory management through ARC, an expressive type system for reliability and maintainability, and seamless interoperability with C and C++. While we initially had concerns that Swift’s server support wasn’t as mature as that found in other ecosystems, both Apple and the open-source community had shown strong commitment to its evolution. Swift had reliably compiled on Linux for a long time; the Swift Server workgroup had coordinated server efforts since 2016; the SwiftNIO library gave us confidence in the foundational capabilities, and Vapor provided all the tools to get us up and running quickly. Convinced by these benefits and the opportunity to use the same language for client and server development, we embarked on a three-year journey to rewrite Things Cloud. We’ve been using it internally for the past two years, and it has now been live in production for over a year. ## The new Swift-based service architecture We’ll outline the core components of our new service architecture, highlighting the Swift packages we use. We’ve found that these components work well together to provide reliability and stability, and we believe this serves as a valuable reference point for others considering a similar transition to Swift. Overview of our new Swift-based service architecture. ### Code * Our **Swift** server codebase has around 30,000 lines of code. It produces a binary of 60 MB, and builds in ten minutes. * It uses **Vapor** as an HTTP web framework, which uses **SwiftNIO** as its underlying network application framework. * We compile a single “monolith” binary from our Swift source code, but use it to run multiple services, each configured by passing different parameters at runtime. * We use **Xcode** for its robust suite of tools for development, debugging, and testing. It provides us with a familiar and consistent experience across both server and client environments. ### Deployment * **AWS** hosts our entire platform, and is entirely managed by **Terraform** , an infrastructure as code tool. * We use a continuous integration pipeline to automate tests and build our Swift code into a **Docker** image. This is then deployed in a **Kubernetes** cluster alongside other components. * The **HAProxy** load balancer is used to route client traffic to the appropriate Swift service in the cluster. ### Storage * Persistent data is stored in **Amazon Aurora MySQL** , a relational database, which we connect to with **MySQLKit**. * To keep the database small, we’re offloading less-used data to **S3** , which we access via the **Soto** package. * More ephemeral data, such as push notifications and caches, is stored in **Redis** , an in-memory key-value database, which we access via **RediStack**. ### Other Services * The **APNSwift** package is used to communicate with the Apple Push Notification service. * **AWS Lambda** , a serverless compute service, powers our **Mail to Things** feature. This process is written in Python 3 due to its mature libraries for the processing of incoming emails. The results are passed to Swift using **Amazon Simple Queue Service**. ### Monitoring * We take the resilience of Things Cloud seriously and go to great lengths to ensure it. * In Swift, we generate JSON logs using our own logger. To produce metrics, we’re using the **Swift Prometheus**. * We use **Amazon CloudWatch** to store and analyze logs and metrics. It triggers Incidents, which reach the responsible engineer via **PagerDuty**. * To test how well our service can recover from transient errors, we employ **chaos testing**. Each day, our self-written chaos agent performs random disruptive actions such as terminating a Swift service or restarting the database. We then verify that the system recovers as expected. ## Results We wanted to thoroughly test the performance and stability of the new Swift service architecture before it was deployed in production. So during the development phase, we deployed the new system alongside the existing legacy system. While the legacy system continued to be the operational service for all requests, the new system also processed them independently using its own logic and database. This approach enabled us to develop and test the new system under real-world conditions without any risk to the user experience. Thanks to the confidence we built in the new system’s robustness and reliability through evaluating it with production workloads, we were able to deploy a hardened system from the very beginning. Now, with over a full year in production, we’re pleased to report that Swift has fulfilled its promise for server-side development. It’s fast and memory-efficient. Our Kubernetes cluster comprises four instances, each with two virtual CPUs and 8 GB of memory, and has handled traffic peaks of up to 500 requests per second. Compared to the legacy system, this setup has led to a more than threefold reduction in compute costs, while response times have shortened dramatically. Comparison between our legacy service and new Swift-based one. And one extra win: Swift’s outstanding performance allowed us to replace our custom C-based push notification service with a Swift-based one; this significantly simplified our codebase and operations. ## Conclusions Swift turned out to be a great choice for server usage. It delivered on everything we had hoped for: We’re now using a modern and expressive programming language, the code runs and performs well, and the Swift ecosystem provides all the integrations we need. With a year of production use, we haven’t encountered a single operational issue. For more information on our journey and experiences, you might enjoy our recent talk at the ServerSide.Swift conference. We encourage other teams to consider using Swift for server-oriented projects. While we chose to undergo a complete rewrite, the gradual adoption of Swift is also an intriguing option, especially considering the recently announced initiative aimed at enhancing Java interoperability. As for us, we believe our server architecture is in its best shape ever, and we’re thrilled about the new features we can build upon this solid foundation.
02.08.2025 12:08 — 👍 0    🔁 0    💬 0    📌 0
Updating the Visual Studio Code extension for Swift Today, we are excited to announce a new version of the Swift extension for Visual Studio Code – now published to the extension marketplace as an official supported release of the Swift team. The aim of this extension is to provide a high-quality, feature-complete extension that makes developing Swift applications on all platforms a seamless experience. As we continue to invest in Swift as a first-class language for cross-platform development, both Apple and the broader developer community are rapidly iterating on the VS Code extension to expand its capabilities for server and cloud, embedded, and Linux and Windows app development. The original extension was developed by members of the Swift Server Working Group, and with its broader scope, they have graciously supported this transition to the GitHub /swiftlang organization and the creation of a new publisher for the extension. For existing Swift developers using VS Code, the transition should be seamless: the old release should automatically install the new extension and disable itself, and moving forward all language features will be provided by the new extension. You’re welcome to uninstall the original extension, which has been renamed to reflect its deprecated status. Further details about the migration can be found on the Swift Forums. If you have any issues migrating, please file an issue or comment on the forum post.
02.08.2025 12:08 — 👍 0    🔁 0    💬 0    📌 0
Swift 6.1 Released Swift 6.1 is now available! This release includes new language enhancements to improve productivity, diagnostics improvements, package traits, and ongoing work to improve data-race safety usability and compile times. Read on for an overview of the changes to the language, package manager, and next steps for getting started with Swift 6.1. ## Language and Standard Library ### Concurrency Swift’s concurrency model allows writing `nonisolated` on properties and functions to indicate that an API is safe to call from any concurrent context. Swift 6.1 extends `nonisolated` to types and extensions. This allows you to write `nonisolated` to prevent `@MainActor` inference on a type, or to apply `nonisolated` to all methods in an extension without having to annotate every method: @MainActor struct S { let id: Int let name: String // mutable state and MainActor methods } nonisolated extension S: CustomStringConvertible, Equatable { var description: String { "id: \(id), name: \(name)" } static func ==(lhs: S, rhs: S) -> Bool { lhs.id == rhs.id } } Swift 6.1 also improves type inference for task groups by inferring the child task result type of `withTaskGroup` and `withThrowingTaskGroup`. Previously, you always had to write the child task result type as an argument when creating the task group: let messages = await withTaskGroup(of: Message.self) { group in for id in ids { group.addTask { await downloadMessage(for: id) } } var messages: [Message] = [] for await message in group { messages.append(message) } return messages } In Swift 6.1, the child task result type can be inferred from the task group closure: // No need for `(of: Message.self)` like before. let messages = await withTaskGroup { group in for id in ids { group.addTask { await downloadMessage(for: id) } } var messages: [Message] = [] for await message in group { messages.append(message) } return messages } The approachability of data-race safety remains an area of active development; you can find an overview of the approach in the vision document for improving the approachability of data-race safety. Many Swift Evolution proposals implementing the features described in the vision document are under active review, and your feedback will help shape these improvements. ### Implementing Objective-C types in Swift Swift 6.1 includes a new attribute, `@implementation`, which can be used together with `@objc` to provide an implementation for a declaration that has been imported from Objective-C. You can write `@objc @implementation` on a Swift `extension` to replace an Objective-C `@implementation` block. You write headers as normal for an Objective-C class, but instead of writing an `@implementation` in an Objective-C file, you write an `@objc @implementation extension` in a Swift file. You can even port an existing class’s implementation to Swift one category at a time without breaking backwards compatibility. ### Productivity enhancements Swift allows including trailing commas in collection literals to make it easy to append, remove, reorder, or comment out the last element as any other element: let rank = [ "Player 1", "Player 3", "Player 2", ] Swift 6.1 extends trailing comma support to tuples, parameter and argument lists, generic parameter lists, closure capture lists, and string interpolations: let numbers = [1, 2, 0, 3, 4, 0, 0, 5] let subsequences = numbers.split( separator: 0, maxSplits: 1, ) In addition to improved development ergonomics, code generation tools like plugins and macros can be simplified, because generating a comma-separated list no longer needs a special condition for the last element. You can find a complete list of language proposals that were accepted through the Swift Evolution process and implemented in Swift 6 on the Swift Evolution dashboard. ## Package and build improvements Swift 6.1 introduces _package traits_ , a new configuration for packages that allows them to offer different APIs and features when used in specific environments, such as Embedded Swift and WebAssembly. Package authors can define a set of traits in their `Package.swift` that their package offers, which provide a way to express conditional compilation and optional dependencies. The package can specify a set of default traits that are enabled in clients, and clients can customize the traits they use when they declare the dependency: dependencies: [ .package( url: "https://github.com/Org/SomePackage.git", from: "1.0.0", traits: [ .default, // enable all of the package's default traits "Embedded" ] ), ] Many editing features, such as jump to definition for APIs in libraries you’re using, are powered by indexing. Before Swift 6.1, indexing occurred when you built your project, which meant that any additions or changes to the library were only surfaced by those editing features after you perform a build. Swift 6.1 enables background indexing by default for SwiftPM projects in SourceKit-LSP. Cross-module and global functionality stays updated as you make changes to your project. ## Swift Testing Swift 6.1 enables custom Swift Testing traits to perform logic before or after tests run in order to share set-up or tear-down logic. If you write a custom trait type which conforms to the new `TestScoping` protocol, you can implement a method to customize the scope in which each test or suite the trait is applied to will execute. For example, you could implement a trait which binds a task local value to a mocked resource: struct MockAPICredentialsTrait: TestTrait, TestScoping { func provideScope(for test: Test, testCase: Test.Case?, performing function: @Sendable () async throws -> Void) async throws { let mockCredentials = APICredentials(apiKey: "fake") try await APICredentials.$current.withValue(mockCredentials) { try await function() } } } extension Trait where Self == MockAPICredentialsTrait { static var mockAPICredentials: Self { Self() } } @Test(.mockAPICredentials) func example() { // Validate API usage, referencing `APICredentials.current`... } For more details, see ST-0007: Test Scoping Traits. Swift Testing in Swift 6.1 also includes refined versions of the `#expect(throws:)` and `#require(throws:)` macros which return their caught errors, making inspecting them in test functions more ergonomic (ST-0006). ## Swift-DocC Swift-DocC introduces a more human readable and human writable alternative for symbol link disambiguation based on parameter type and return type information. For example, consider these three function overloads with different parameter types and return types: func doSomething(first: String, second: Int) -> Double func doSomething(first: String?, second: Int) -> Float func doSomething(first: String?, second: Int) -> Double Previously, if you wrote a link to one of these overloads you needed to include a short hash of that symbol’s unique identifier to disambiguate the link and uniquely reference the specific overload. Swift-DocC’s warnings aided in writing these hashes but a person can’t decode the resulting hash suffix (`-3c5j`) to determine which overload the link is referring to. Now, you can use a combination of parameter types and return types—like `-(String,_)`, `->Float,` or `-(String?,_)->Double`—to disambiguate the link and uniquely reference a specific overload. You can discover the minimal combination of parameter types and return types for each overload from Swift-DocC’s warnings about ambiguous symbol links. For more details, see the Ambiguous Symbol Links section of Linking to Symbols and Other Content. ## Install Swift 6.1 You can try out these exciting new developments in Swift 6.1 today! If you’re building apps for Apple platforms, Swift 6.1 is included in Xcode 16.3, now available from the App Store. And the easiest way to install the standalone Swift 6.1 toolchain is using swiftly, the new Swift version manager that runs on macOS and Linux. Additional installation methods, including for Windows, are included on the Install Swift page.
02.08.2025 12:08 — 👍 0    🔁 0    💬 0    📌 0
Introducing swiftly 1.0 Today we’re delighted to introduce the first stable release of swiftly, a Swift version manager that takes the pain out of installing, managing and updating your Swift toolchain. The latest version of Swift is bundled with Xcode for writing apps for Apple platforms. But perhaps you want to install Swift on a different platform like Linux, or use a different version of the toolchain for building services or command line tools. Downloading, extracting and installing a trusted build of Swift along with the relevant dependencies for your operating system can require quite a few manual and error-prone steps. swiftly has been around for some years as a community-supported tool for Swift developers using Linux. With this release, we’re officially supporting it as part of the core Swift toolchain, including hosting it as part of the Swift GitHub organization. We’ve also added macOS support to make it easier to install Swift separately from Xcode. ## Introducing swiftly swiftly is the best tool to install the standalone toolchain, providing commands to install Swift on a new system, update to the latest stable version, and experiment or test with nightly snapshots or older versions. It also makes it easy to switch effortlessly between multiple installed toolchains. You can even add a file to your project repository so swiftly will use the same toolchain version for all members of your development team. Naturally, swiftly itself is written in Swift, and is able to update itself to the latest version. ## Quick tour Let’s take a look at some of the features of swiftly! To get started, visit swift.org/install and install it. swiftly will provide directions after installation if there are any system packages, or shell commands needed for smooth operation of the new toolchain. The latest Swift toolchain is installed as the default, so you can immediately use it to start a new project. For example: $ swift package init The `swiftly use` command selects the default toolchain for Swift commands (e.g. `swift test`, `swift build`): $ swiftly use 6.0.3 $ swift --version -- Apple Swift version 6.0.3 (swiftlang-6.0.3.1.2 clang-1600.0.28.6) Target: arm64-apple-macosx15.0 At a later point, if there’s a new release of Swift you can install it alongside the existing toolchain with the `latest` command: $ swiftly install latest Pre-release of versions of Swift are available, including nightly “snapshot” toolchains. They can be easily listed using swiftly: $ swiftly list-available main-snapshot -- Available main development snapshot toolchains ---------------------------------------------- main-snapshot-2025-03-25 ... Once you’ve identified a snapshot toolchain, it can be installed using its name: $ swiftly install main-snapshot-2025-03-25 -- Installing main-snapshot-2025-03-25 Another way to temporarily use a specific version of Swift is to use the special ‘+’ selector. With this syntax, you don’t need to first switch to a different toolchain: $ swiftly run lldb +main-snapshot-2025-03-25 -- (lldb) _ If you’re building a SwiftPM project in a team setting and want to enforce a common version of the Swift toolchain on all contributors, simply create a `.swift-version` file in the root of your project folder with the desired version (e.g. “6.0.3”). As swiftly is updated with new features and bug fixes, you can run `swiftly self-update` to check and install new releases. ## How swiftly works By writing swiftly in Swift, we’re able to take advantage of the language’s features, support, and ecosystem of related projects. Swift comes with standard library features for working with the filesystem in its Foundation module. For network operations Async HTTP Client is there to work the HTTP requests. And to retrieve the latest Swift release, swiftly uses the Swift OpenAPI plugin to generate the code to interact with the swift.org website. Lastly, it takes advantage of Swift’s interoperability with C to use the existing libarchive library to work with archives. swiftly uses libarchive to extract the toolchains downloaded from the Swift website and the integration is simple. It can be challenging to build shell programs that work well across multiple platforms with minimal system dependencies; this motivated us to switch swiftly away from using a shell program to install it and become a self-installing binary application. swiftly has access to excellent argument parsing capabilities, beautiful `--help` screens, and the full standard library. The only remaining problem was being able to deliver the operating system and processor architecture specific binary to the users system with simplicity. The swift.org website helps with operating system detection, but it cannot reliably detect the Linux distribution. Luckily, there is the Swift Static Linux SDK that makes binaries that work with a wide range of distributions. The processor architecture can be determined on most unixes using `uname -m` . The result of all of this is the simplicity of a copy and paste from the website to your terminal and get started with Swift. ## Installing Swift, swiftly Moving forward, swiftly will become the default way to install Swift outside of Xcode. The initial version supports macOS and a variety of Linux distributions, including Ubuntu, Debian, Fedora, Red Hat Enterprise Linux and Amazon Linux. The swiftly documentation provides further information about using swiftly in a CI/CD environment, as well as setting proxy servers and custom install locations for enterprise environments. swiftly is an open source project, and so you can raise new issues or contribute pull requests at its GitHub repository. You can also ask questions or discuss swiftly on the Swift Forums. Special thanks to Patrick Freed for creating swiftly, contributing it to the Swift organization, and his continued contributions to this valuable tool. The community is what makes Swift amazing!
02.08.2025 12:08 — 👍 0    🔁 0    💬 0    📌 0
Swift at Apple: Migrating the Password Monitoring service from Java _Swift is heavily used in production for building cloud services at Apple, with incredible results. Last year, the Password Monitoring service was rewritten in Swift, handling multiple billions of requests per day from devices all over the world. In comparison with the previous Java service, the updated backend delivers a 40% increase in performance, along with improved scalability, security, and availability._ The Passwords app, introduced in the fall of 2024, helps users manage their passwords, passkeys, and verification codes. It allows them to store, autofill, and generate strong passwords that can be shared across all their devices, as well as share passwords with trusted contacts. One security feature included in the app is Password Monitoring, which warns users if one of their saved passwords shows up in a data leak. This feature has a server component, running on Linux-based infrastructure, that is maintained by Apple. On a regular interval, Password Monitoring checks a user’s passwords against a continuously updated and curated list of passwords that are known to have been exposed in a leak. Importantly, this task is handled in a thoughtful, privacy-preserving way that never reveals users’ passwords to Apple. A detailed discussion of how this is done using the cryptographic private set intersection protocol is in the Password Monitoring section of the Apple Platform Security guide. The migration from Java to Swift was motivated by a need to scale the Password Monitoring service in a performant way. The layered encryption module used by Password Monitoring requires a significant amount of computation for each request, yet the overall service needs to respond quickly even when under high load. ## Choosing Swift for increased performance For years, our team relied on Java to power large-scale, mission-critical services because of its proven stability and performance. However, Java’s memory management approach no longer aligns with our growing demands and efficiency goals. Instead of simply expanding hardware resources, we were seeking a more-efficient language to support our growth while reducing server overhead. Prior to seeking a replacement language, we sought ways of tuning the JVM to achieve the performance required. Java’s G1 Garbage Collector (GC) mitigated some limitations of earlier collectors by introducing features like predictable pause times, region-based collection, and concurrent processing. However, even with these advancements, managing garbage collection at scale remains a challenge due to issues like prolonged GC pauses under high loads, increased performance overhead, and the complexity of fine-tuning for diverse workloads. One of the challenges faced by our Java service was its inability to quickly provision and decommission instances due to the overhead of the JVM. The Password Monitoring service runs globally, so service load can greatly fluctuate throughout the day, even with client-side techniques to smooth over the distribution of traffic. The peak and trough of a day differ by approximately 50% regionally. To efficiently manage this, we aim to scale down when demand is low and scale up as demand peaks in different regions. A faster bootstrap time is a crucial requirement to support this dynamic scaling strategy. Given the scale of our application and the volume of traffic we manage daily, the decision to transition from Java to another language was not made lightly. We evaluated our options, and found only a few languages that could help us achieve our goals. While you might expect that Apple would automatically choose Swift, we were pleasantly surprised by how well it fit the unique needs of a cloud-based service like ours. Swift has expressive syntax that was easy to learn, and could deliver the performance improvements necessary to meet the demands of our compute workloads. We decided to take a significant leap and started a rewrite of the Password Monitoring backend using Swift. ## Our experience developing with Swift We began rewriting our service using Vapor, a Swift web framework that provided Routing, Controller, and Content modules that we were able to build upon. Our service had additional requirements that led us to create a few custom packages with essential functionality: elliptic curve operations that are crucial for implementing password monitoring, auditing, configuration, error handling, and custom middleware. One of the most significant aspects of Swift that impressed us was its emphasis on protocols. In Java, we relied heavily on inheritance, which can lead to complex class hierarchies and tight coupling. Swift’s approach of protocols and generics promotes modularity and reusability by allowing classes, structs, and enums to share common protocols, enabling a more flexible and scalable codebase. This shift in mindset encouraged us to think in terms of behaviors rather than concrete classes, resulting in cleaner and more maintainable code. Safety is another area where Swift takes a distinctive approach compared to Java. For example, Swift’s optional type and safe unwrapping mechanisms eliminate the need for null checks everywhere, reducing the risk of null pointer exceptions and enhancing code readability. This safety-first approach ingrained throughout Swift’s language design, whether it is deterministic deallocation, copy-on-write (CoW), or value types, makes it inherently less prone to runtime errors. Swift’s async/await support is a nice addition, streamlining how we handle async tasks. Previously, managing async operations often involved complex callback patterns or external libraries. Swift’s async/await syntax simplifies this process, making it more intuitive and less error-prone. We can now write async code that reads like sync code, leading to more readable, testable, and maintainable concurrency handling—especially critical in high-load, multi-threaded environments. Overall, our experience with Swift has been overwhelmingly positive and we were able to finish the rewrite much faster than initially estimated. Swift allowed us to write smaller, less verbose, and more expressive codebases (close to 85% reduction in lines of code) that are highly readable while prioritizing safety and efficiency. Our service benefited from a diverse ecosystem of Swift packages, including logging frameworks, a Cassandra client, and crypto libraries that were readily available. In addition to an excellent support system and tooling, Swift’s inherent emphasis on modularity and extensibility helped future-proof and simplify the integration and customizations needed for our service-specific functions. ## Takeaways for future Swift on server development We benchmarked performance throughout the process of development and deployment, allowing us to discover the trait of the Swift programming language that delighted us the most — its efficiency. Swift’s deterministic memory management led to a much lower memory threshold for our service. Not only were our initial results heartening, but after a few iterations of performance improvements, we had close to 40% throughput gain with latencies under 1 ms for 99.9% of requests on our current production hardware. Additionally, the new service had a much smaller memory footprint per instance — in the 100s of megabytes — an order of magnitude smaller compared to the 10s of gigabytes our Java implementation needed under peak load to sustain the same throughput and latencies. The service runs on Kubernetes, and the migration’s efficiency improvements allowed us to release about 50% of its capacity for other workloads. Our Swift implementation has run smoothly and efficiently in production, making it worth the effort we put into this migration. In addition to outperforming our previous Java-based application, Swift delivered better performance consistency, enhanced safety features, and robust reliability — all while requiring fewer resources by utilizing memory and CPU efficiently. With fewer lines of boilerplate code and more flexible design patterns that we used, we look forward to simplified maintenance of our application. Swift was a powerful choice for building fast, resilient, and maintainable applications in our high-demand environment.
02.08.2025 12:08 — 👍 0    🔁 0    💬 0    📌 0
Redesigned Swift.org is now live Over the past few months, the website workgroup has been redesigning Swift.org. On behalf of the website workgroup, I’m pleased to announce that we have merged the initial changes. Our goal with the site redesign has been to make Swift.org more approachable for newcomers to Swift, highlight the language’s technical strengths, and make it easy to get started. That led to a focus on the website’s appearance, improving the user experience, and emphasizing important features such as Swift’s multiplatform support. Today’s release includes refreshed home and install pages. Additionally, new pages have been designed to explore Swift use cases, including cloud services, command line tools, and embedded software. Looking forward, we plan to take an iterative approach to improving the website, including pushing changes live as we complete their design and implementation. ## Brand new design We explored several design options and found that the latest design conveys the fluidity and creativity of Swift through the splash of orange and the bird animation in the background. ## Curated content and examples The homepage now highlights Swift’s strengths alongside code examples that illustrate them. Additionally, we showcase various types of software that can be developed using Swift; these new use case pages provide information such as relevant packages, examples of Swift in action, code snippets, and links to resources for further learning. ## Next Steps We look forward to hearing your feedback on this first set of changes as we continue to redesign other sections of the site. There are several ways to offer feedback on the redesign and to get involved: * A forum announcement has been shared on the forums that can be used for discussion, and the website repository has GitHub issues. * The website itself is open source, and your contributions to the swiftlang/swift-org-website repository are welcome. * The Swift Information Architecture Project is an ongoing effort that has helped inform decisions related to the site redesign. Thank you to the website workgroup and community members for contributing to these improvements.
02.08.2025 12:08 — 👍 0    🔁 1    💬 0    📌 0
Announcing Swift 6 We’re delighted to announce the general availability of Swift 6. This is a major new release that expands Swift to more platforms and domains. Many people know of Swift as a language for app development, with a million apps on the App Store. But Swift is great for more than just apps. Swift’s safety, speed, and approachability make it a great choice for many other use cases including libraries, internet-scale services, and the most performance-critical and secure code. Swift 6 scales even further through new low-level programming features, an embedded Swift language subset, expanded Linux and Windows support, new cross-platform APIs including the new Swift Testing library, and more. Read on for a deep dive into changes to the language, standard libraries, debugging, platform support, and next steps for getting started with Swift 6. ## Language and Standard Library ### Concurrency Swift has long offered memory safety, ensuring that variables are initialized before they’re used, memory isn’t accessed after it’s been deallocated, and array indices are checked for out-of-bounds errors. Swift 6 now includes a new, opt-in language mode that extends Swift’s safety guarantees to prevent data races in concurrent code by diagnosing potential data races in your code as compiler errors. Data-race safety checks were previously available as warnings in Swift 5.10 through the `-strict-concurrency=complete` compiler flag. Thanks to improved `Sendable` inference and new compiler analysis for transferring mutable state from one actor to another, Swift 6 warnings about data-race safety have fewer false positives. You can find more information about the Swift 6 language mode and how to migrate at Swift.org/migration. Swift 6 marks the start of the journey to make data-race safety dramatically easier. The usability of data-race safety remains an area of active development, and your feedback will help shape future improvements. Swift 6 also comes with a new Synchronization library for low-level concurrency APIs, including atomic operations and a new mutex API. ### Typed throws Swift 6 enables functions to specify the type of error that they throw as part of their signature. This feature is useful in generic code that forwards along errors thrown in client code, or in resource-constrained environments that cannot allocate memory, such as in embedded Swift code. For example: func parseRecord(from string: String) throws(ParseError) -> Record { // ... } A call to `parseRecord(from:)` will either return a `Record` instance or throw an error of type `ParseError`. A `do..catch` block will infer `ParseError` as the type of the `error` variable: do { let record = try parseRecord(from: myString) } catch { // 'error' has type 'ParseError' } Typed throws generalizes over throwing and non-throwing functions. A function that is specified as `throws` (without a specific error type) is equivalent to one that specifies `throws(any Error)`, whereas a non-throwing function is equivalent to one that specifies `throws(Never)`. Calls to functions that are `throws(Never)` are non-throwing and don’t require error handling at the call site. Typed throws can also be used in generic functions to propagate error types from parameters, in a manner that is more precise than `rethrows`. For example, the `Sequence.map` method can propagate the thrown error type from its closure parameter, indicating that it only throws the same type of errors as the closure: extension Sequence { func map<T, E>(_ body: (Element) throws(E) -> T) throws(E) -> [T] { // ... } } When given a closure that throws `ParseError`, `map` will throw `ParseError`. When given a non-throwing closure, `E` is inferred to `Never` and `map` will not throw. ### Ownership Swift 5.9 introduced non-copyable types with the `~Copyable` syntax for modeling resources with unique ownership, and writing performance-conscious code by eliminating the runtime overhead associated with copying. Swift 6 now supports these types with the generics system, making it possible to write generic code that works with both copyable and non-copyable types. For example: protocol Drinkable: ~Copyable { consuming func use() } struct Coffee: Drinkable, ~Copyable { /* ... */ } struct Water: Drinkable { /* ... */ } func drink(item: consuming some Drinkable & ~Copyable) { item.use() } drink(item: Coffee()) drink(item: Water()) The `Drinkable` protocol has no requirement that its conforming types are `Copyable`. This means both the non-copyable type `Coffee` and copyable type `Water` can be passed into the generic `drink` function. Switch statements can now be written to avoid copying within enum pattern-matching operations. This means that switch statements can be used with non-copyable payloads and can also provide performance benefits for copyable payloads, especially those based on copy-on-write containers like `Array` and `Dictionary`. Non-copyable types are already used throughout the standard libraries. For instance, the new `Atomic` type in the Synchronization library is based on `~Copyable`, `Optional` and `Result` can now wrap non-copyable types, and the unsafe buffer pointer types can now point to non-copyable elements. C++ interoperability also uses non-copyable types to expose C++ move-only types to Swift. ### C++ interoperability Swift 5.9 introduced bidirectional interoperability with C++ to seamlessly bring Swift to more existing projects. Swift 6 expands interoperability support to C++ move-only types, virtual methods, default arguments, and more standard library types including `std::map` and `std::optional`. C++ types that do not have a copy constructor can now be accessed from Swift 6 as non-copyable types with `~Copyable`. And for those times when it’s useful to expose a C++ type with a copy constructor as `~Copyable` in Swift for better performance, a new `SWIFT_NONCOPYABLE` annotation can be applied to the C++ type. Swift now also supports calls of C++ virtual methods on types annotated as `SWIFT_SHARED_REFERENCE` or `SWIFT_IMMORTAL_REFERENCE`. When calling C++ functions or methods that have default argument values for some of their parameters, Swift now respects these default values, rather than requiring you to explicitly pass an argument. ### Embedded Swift Swift 6 includes a preview of Embedded Swift, a language subset and compilation mode suitable for embedded software development, such as programming microcontrollers. The toolchain supports ARM and RISC-V bare-metal targets. Embedded Swift produces small and standalone binaries by relying on generic specialization. Since it doesn’t rely on a runtime or type metadata, Embedded Swift is suitable for platforms with tight memory constraints as well as use in low-level environments with limited runtime dependencies. Embedded Swift remains an experimental feature, with ongoing development before stable support in a future Swift release. ### 128-bit Integers Swift 6 rounds out the set of low-level integer primitives with the addition of signed and unsigned 128-bit integer types. These are available on all Swift platforms, and provide the same API as other fixed-width integer types in the standard library. ### Productivity enhancements Swift 6 introduces a number of productivity enhancements, including `count(where:)` to streamline counting the number of elements in a sequence that satisfy a predicate, pack iteration for writing natural `for`-loops over the elements in a value parameter pack, access control for imports to keep implementation details from leaking into your public APIs, `@attached(body)` macros for synthesizing and augmenting function implementations, expression macros as default arguments, and more. You can find a complete list of language proposals that were accepted through the Swift Evolution process and implemented in Swift 6 on the Swift Evolution dashboard. ## Debugging ### Custom LLDB summaries with `@DebugDescription` @DebugDescription` section" href="#custom-lldb-summaries-with-debugdescription"> Swift 6 provides a new debugging macro to easily customize how an object is displayed in LLDB when using the `p` command, and in the variables view in Xcode and VSCode, by using a formatting scheme that does not run arbitrary code. Types that conform to `CustomDebugStringConvertible` provide a `debugDescription` property that returns a string describing the object. In LLDB, the `po` command calls this computed property on an object. In contrast, the `p` command uses LLDB’s type summary formatters to directly format the object using its stored property values. `@DebugDescription` is a new macro in the standard library which lets you specify LLDB type summaries for your own types directly in code. The macro processes the `debugDescription` property, translating simple string interpolations involving stored properties into LLDB type summaries. This allows LLDB to use your custom formatting even when using `p`, and also in Xcode or VSCode’s variable display windows. The macro can use an existing conformance to `CustomDebugStringConvertible`, or you can provide a separate string interpolation only for use in LLDB’s `p` command. Providing a separate LLDB description string is useful if your `CustomDebugStringConvertible` implementation doesn’t meet the requirements of the `@DebugDescription` macro, or if you’re familiar with the LLDB Summary String syntax and you want to use it directly. For example, the following code customizes how `po` in LLDB displays the `Organization` type with a conformance to `CustomDebugStringConvertible`, and the `@DebugDescription` macro exposes this custom formatting to the `p` command and the variables view: @DebugDescription struct Organization: CustomDebugStringConvertible { var id: String var name: String var manager: Person // ... and more var debugDescription: String { "#\(id) \(name) [\(manager.name)]" } } (lldb) p myOrg (Organization) myOrg = "`#100 Worldwide Travel [Jonathan Swift]`" ### Improved startup performance with explicit modules Swift 6 dramatically improves startup performance in the debugger when you use explicit module builds. When debugging locally-built code, LLDB can now import explicitly-built Swift and Clang modules directly from the project build artifacts. This avoids the need to recompile implicit Clang module dependencies from source, which can take a long time, and it’s very sensitive to issues with header search paths. If the first `p` or `po` command in LLDB takes a long time due to Clang module compilation, or if your debugging is frequently blocked by Clang header import problems, consider adopting explicit modules in your project! ## Libraries ### Foundation Swift 6 unifies the implementation of Foundation across all platforms. The modern, portable Swift implementation provides consistency across platforms, it’s more robust, and it’s open source. macOS and iOS started using the Swift implementation of Foundation alongside Swift 5.9, and Swift 6 brings these improvements to Linux and Windows. Core types like `JSONDecoder`, `URL`, `Calendar`, `FileManager`, `ProcessInfo`, and more have been completely reimplemented in Swift. These types share their implementation with macOS 15 and iOS 18, providing a new level of cross-platform consistency, reliability, and performance. Recently released APIs like `FormatStyle`, `ParseStrategy`, `Predicate`, and `JSON5`, from past macOS and iOS releases are now available on all Swift platforms. New Foundation APIs like `Expression`, calendar enumeration improvements, calendar recurrence rules, format style enhancements, and more are available simultaneously on macOS, iOS, Linux, and Windows - and they were built with community involvement. If your Linux or Windows app imports the `Foundation` library from the Swift toolchain today, you get all of these improvements for free. And if your app is particularly sensitive to binary size, you can now import the `FoundationEssentials` library, which provides a more targeted subset of Foundation’s features that omits internationalization and localization data. ### Swift Testing Swift 6 introduces Swift Testing, a new testing library designed from the ground up for Swift. It includes expressive APIs that make it easy to write and organize tests. It provides detailed output when a test fails using macros like `#expect`. And it scales to large codebases with features like parameterization to easily repeat a test with different arguments. For example: @Test("Continents mentioned in videos", arguments: [ "A Beach", "By the Lake", "Camping in the Woods" ]) func mentionedContinents(videoName: String) async throws { let videoLibrary = try await VideoLibrary() let video = try #require(await videoLibrary.video(named: videoName)) #expect(video.mentionedContinents.count <= 3) } Swift Testing takes full advantage of macros. Its `@Test` and `@Suite` attached macros declare test functions and suite types respectively, and they accept arguments (known as traits) to customize various behaviors. The `#expect` and `#require` expression macros validate expected behaviors, and capture rich representation of expressions and their sub-values to produce detailed failure messages. Since Swift Testing is included directly in Swift 6 toolchains, you can `import Testing` without needing to declare a package dependency. This means your tests do not need to build Swift Testing or its dependencies (including swift-syntax), and its macro implementation comes prebuilt. The package manager in Swift 6 automatically builds and runs Swift Testing tests in addition to XCTests (if present), and shows results from both libraries in log output. Swift Testing supports all platforms that Swift officially supports, including all Apple platforms, Linux, and Windows. To learn more about this new open source project, visit the swift-testing repository on GitHub, and get involved with its ongoing development on the forums. ## Platform Support Swift is designed to support development and execution on all major operating systems, and platform consistency and expansion underpins Swift’s ability to reach new programming domains. Swift 6 brings major improvements to Linux and Windows across the board, including support for more Linux distributions and Windows architectures. Toolchains for all of the following platforms are available for download from Swift.org/install. ### Fully static SDK for Linux Swift 6 supports building fully statically linked executables for Linux; these have no external dependencies, so they are ideal for situations where you want to copy a program directly onto a system or into a container and run it without installing any extra software. The SDK can also be used to cross-compile to Linux from other platforms. Learn how to get started with the static SDK for Linux on Swift.org. ### New Linux distributions Swift 6 adds official support and testing for Debian and Fedora, as well as on Ubuntu 24.04. ### Windows build performance Prebuilt toolchains are now available for the arm64 architecture, which provides improved compiler performance for Windows on ARM hosts. In Swift 6, the Swift package manager also parallelizes builds across multiple cores on Windows by default. On a 10-core machine, this can improve build performance by up to a factor of 10! ## Next Steps ### Download Swift 6 You can try out these exciting new developments in Swift 6 today! Install the official Swift 6 toolchains for macOS, Linux, and Windows at Swift.org/install. ### Get started with Swift The Swift Programming Language book has been updated to reflect the latest Swift 6 syntax and features. It serves as the official Swift guide and an excellent starting point for learning the language. To help kickstart your Swift journey, Swift.org/getting-started offers tutorials for various use cases, including building a cross-platform library, a web service using Vapor, and an embedded application for a microcontroller. There are also articles for diving deeper into some of Swift’s most popular features. ### Explore the package ecosystem The Swift package ecosystem is continuously growing with new technologies to help you with a variety of tasks in your projects. You can explore package highlights at Swift.org/packages, which features popular package categories and a selection of new and notable packages that are hand-curated from an open nomination process every month. ### Get involved Your experience with Swift 6 and your feedback can help shape the future evolution of the language, the tools, the package ecosystem, and the community. You can get involved by sharing your packages, documentation improvements, educational content, bug reports and enhancement requests, code contributions, and participating in forum discussions. Learn more at Swift.org/contributing. Swift 6 is the culmination of countless contributions from members across the Swift community, and it marks a decade of building this incredible language, ecosystem, and community together. Thank you to everyone who participated in development and provided feedback. Your contributions make Swift a better language.
01.08.2025 08:08 — 👍 1    🔁 0    💬 0    📌 0
The Next Chapter in Swift Build Technologies Swift continues to grow in popularity as a cross-platform language supporting a wide variety of use cases, with support on a variety of embedded devices, form factors that encompass wearables to server, and a wide variety of operating systems. As Swift expands, there’s value in investing in matching cross-platform build tools that provide a powerful, consistent, and flexible experience across the ecosystem. As a foundational step in this new chapter of Swift build technologies, today Apple is open sourcing Swift Build, a powerful and extensible build engine that provides a set of build rules for building Swift projects. Swift Build is the engine used by Xcode, which supports millions of apps in the App Store as well as the internal build process for Apple’s own operating systems. The open source repository also includes support for targeting Linux and Windows. ## Introducing Swift Build The primary responsibility of the build system is to transform user-authored inputs (such as a project description and source code) into output artifacts like command line tools, libraries, and applications. Build systems play an important role in providing a great developer experience, enabling higher level features which determine how users architect and work with their projects. Furthermore, the performance and reliability of a build system has a direct impact on developer productivity. Swift Build is an infrastructural component designed to plan and execute builds requested by a higher-level client like Swift Package Manager or Xcode. It builds on top of the existing llbuild project to add capabilities including: * Robust integration with the Swift compiler to reliably and efficiently coordinate the build of Swift projects * Support for a wide variety of product types including libraries, command line tools, and GUI applications with advanced build configuration options * Build graph optimizations that maximize parallelism when building Swift and C code ## Roadmap for Swift Build Compared to the build engine in Xcode, the build engine in Swift Package Manager is fairly simple. On Apple platforms, having two different ways to build packages has also led to user confusion when the two implementations’ behavior didn’t match. Contributing Xcode’s build engine to the Swift project and developing it in open source alongside the Swift compiler provides the tools necessary to address these problems and deliver a great builds experience to all Swift users. With this release, SwiftPM now has the opportunity to offer a unified build execution engine across all platforms. This change should be transparent to users and maintain full compatibility with all existing packages while delivering a consistent cross-platform experience. At the same time, it lays the foundation to enable new features and improvements across all platforms and tools, and unlocks new performance optimizations and developer-facing features. As a small first step towards this vision, today the team is submitting a pull request to begin the process of integrating support for Swift Build in SwiftPM as an alternate build engine. In the coming months, we’d like to collaborate with the community to complete the work of unifying build system integrations so users can benefit from future tooling improvements across all platforms and project models. We believe this is an important step in continuing to enable a healthy package ecosystem where developers can rely on a consistent, polished development experience — no matter what IDE they’re using or platform they’re targeting. We’ll be sharing more details about this work on the Swift forums, and we’re looking forward to hearing others’ feedback! ## An invitation to participate We look forward to working with the community to continue evolving how we build Swift code. You can find the `swift-build` repository in the Swift organization on GitHub, including a README and documentation describing how to build and contribute. Contributions via pull requests and issues are welcome, and we’d also love to solicit feedback and ideas for improvements on the Swift forum. This is an exciting new chapter for Swift’s build system, and we’re looking forward to all the potential it opens for Swift!
01.08.2025 08:08 — 👍 0    🔁 0    💬 0    📌 0
How Swift's server support powers Things Cloud You might be familiar with Things, a delightful personal task manager that has won two Apple Design Awards and is available across Apple devices including iPhone, iPad, Mac, Apple Watch, and Apple Vision Pro. At Cultured Code, the team behind Things, we care about a great user experience across every aspect of the product. This extends to our server back end, and after a rewrite our Things Cloud service has transitioned entirely to Swift. Over the past year in production, Swift has consistently proven to be reliable, performant, and remarkably well-suited for our server-side need. Things Cloud serves as the backbone of the app’s experience, silently synchronizing to-dos across devices. The robustness of this work is ensured by a rigorous theoretical foundation, inspired by operational transformations and Git’s internals. After twelve years in production, Things Cloud has earned our users’ trust in its reliability. But despite the enduring strength of the architecture itself, the technology stack lagged behind. Things Cloud synchronizes to-dos across different devices. ## Switching to Swift Our legacy Things Cloud service was built on Python 2 and Google App Engine. While it was stable, it suffered from a growing list of limitations. In particular, slow response times impacted the user experience, high memory usage drove up infrastructure costs, and Python’s lack of static typing made every change risky. For our push notification system to be fast, we even had to develop a custom C-based service. As these issues accumulated and several deprecations loomed, we realized we needed a change. A full rewrite is usually a last resort, but in our case, it was the only viable path for Things Cloud. We explored various programming languages including Java, Python 3, Go, and even C++. However, Swift – which was already a core part of our client apps – stood out for its potential and unique benefits. Swift promised excellent performance, predictable memory management through ARC, an expressive type system for reliability and maintainability, and seamless interoperability with C and C++. While we initially had concerns that Swift’s server support wasn’t as mature as that found in other ecosystems, both Apple and the open-source community had shown strong commitment to its evolution. Swift had reliably compiled on Linux for a long time; the Swift Server workgroup had coordinated server efforts since 2016; the SwiftNIO library gave us confidence in the foundational capabilities, and Vapor provided all the tools to get us up and running quickly. Convinced by these benefits and the opportunity to use the same language for client and server development, we embarked on a three-year journey to rewrite Things Cloud. We’ve been using it internally for the past two years, and it has now been live in production for over a year. ## The new Swift-based service architecture We’ll outline the core components of our new service architecture, highlighting the Swift packages we use. We’ve found that these components work well together to provide reliability and stability, and we believe this serves as a valuable reference point for others considering a similar transition to Swift. Overview of our new Swift-based service architecture. ### Code * Our **Swift** server codebase has around 30,000 lines of code. It produces a binary of 60 MB, and builds in ten minutes. * It uses **Vapor** as an HTTP web framework, which uses **SwiftNIO** as its underlying network application framework. * We compile a single “monolith” binary from our Swift source code, but use it to run multiple services, each configured by passing different parameters at runtime. * We use **Xcode** for its robust suite of tools for development, debugging, and testing. It provides us with a familiar and consistent experience across both server and client environments. ### Deployment * **AWS** hosts our entire platform, and is entirely managed by **Terraform** , an infrastructure as code tool. * We use a continuous integration pipeline to automate tests and build our Swift code into a **Docker** image. This is then deployed in a **Kubernetes** cluster alongside other components. * The **HAProxy** load balancer is used to route client traffic to the appropriate Swift service in the cluster. ### Storage * Persistent data is stored in **Amazon Aurora MySQL** , a relational database, which we connect to with **MySQLKit**. * To keep the database small, we’re offloading less-used data to **S3** , which we access via the **Soto** package. * More ephemeral data, such as push notifications and caches, is stored in **Redis** , an in-memory key-value database, which we access via **RediStack**. ### Other Services * The **APNSwift** package is used to communicate with the Apple Push Notification service. * **AWS Lambda** , a serverless compute service, powers our **Mail to Things** feature. This process is written in Python 3 due to its mature libraries for the processing of incoming emails. The results are passed to Swift using **Amazon Simple Queue Service**. ### Monitoring * We take the resilience of Things Cloud seriously and go to great lengths to ensure it. * In Swift, we generate JSON logs using our own logger. To produce metrics, we’re using the **Swift Prometheus**. * We use **Amazon CloudWatch** to store and analyze logs and metrics. It triggers Incidents, which reach the responsible engineer via **PagerDuty**. * To test how well our service can recover from transient errors, we employ **chaos testing**. Each day, our self-written chaos agent performs random disruptive actions such as terminating a Swift service or restarting the database. We then verify that the system recovers as expected. ## Results We wanted to thoroughly test the performance and stability of the new Swift service architecture before it was deployed in production. So during the development phase, we deployed the new system alongside the existing legacy system. While the legacy system continued to be the operational service for all requests, the new system also processed them independently using its own logic and database. This approach enabled us to develop and test the new system under real-world conditions without any risk to the user experience. Thanks to the confidence we built in the new system’s robustness and reliability through evaluating it with production workloads, we were able to deploy a hardened system from the very beginning. Now, with over a full year in production, we’re pleased to report that Swift has fulfilled its promise for server-side development. It’s fast and memory-efficient. Our Kubernetes cluster comprises four instances, each with two virtual CPUs and 8 GB of memory, and has handled traffic peaks of up to 500 requests per second. Compared to the legacy system, this setup has led to a more than threefold reduction in compute costs, while response times have shortened dramatically. Comparison between our legacy service and new Swift-based one. And one extra win: Swift’s outstanding performance allowed us to replace our custom C-based push notification service with a Swift-based one; this significantly simplified our codebase and operations. ## Conclusions Swift turned out to be a great choice for server usage. It delivered on everything we had hoped for: We’re now using a modern and expressive programming language, the code runs and performs well, and the Swift ecosystem provides all the integrations we need. With a year of production use, we haven’t encountered a single operational issue. For more information on our journey and experiences, you might enjoy our recent talk at the ServerSide.Swift conference. We encourage other teams to consider using Swift for server-oriented projects. While we chose to undergo a complete rewrite, the gradual adoption of Swift is also an intriguing option, especially considering the recently announced initiative aimed at enhancing Java interoperability. As for us, we believe our server architecture is in its best shape ever, and we’re thrilled about the new features we can build upon this solid foundation.
01.08.2025 08:08 — 👍 0    🔁 0    💬 0    📌 0
Introducing gRPC Swift 2 Say hello to gRPC Swift 2: a major update that brings first-class concurrency support and more expressive APIs for a seamless developer experience. Inconsistent and poorly documented service APIs create integration headaches for developers. gRPC is a modern, high-performance framework for building service APIs, enabling efficient communication between systems over a network. Since services may be written with a different language than their clients, most gRPC services use Protocol Buffers (or “protobufs”) to define their APIs and the messages exchanged between clients and servers. Service contracts are defined in a neutral, cross-platform format using `.proto` files. This is the foundation of your service, not an artefact of its implementation. And thanks to the format’s efficient binary serialization, these messages are typically smaller and faster to process than other standard formats like JSON. gRPC Swift is one of a family of similar tools that use the Protocol Buffers contract to generate code in the language you’re working with, making it easy to build clients and servers that adhere to your service contract. And the new gRPC Swift 2 offers an idiomatic, cross-platform, performant and feature-rich library for building highly-scalable services. This release is a major update that takes advantage of many modern Swift features for cross-platform services development. When gRPC Swift was first developed back in 2018, Swift had not yet introduced concurrency features like async/await, so it was instead based on SwiftNIO’s event-driven concurrency model. For developers unfamiliar with these concepts, the prior version of gRPC Swift presented a steep learning curve. Now that Swift’s modern concurrency model is fully established, we seized the opportunity to rethink gRPC Swift for today’s Swift, incorporating lessons learned from our years of use at Apple for building internet-scale services. ## Highlights * Modern, flexible, and easy-to-use APIs with idiomatic generated code. * Full support for building services and clients on Linux and Apple platforms. * Pluggable transports including a high-performance HTTP/2 transport built on top of SwiftNIO, and an in-process transport which is great for testing. * Smart client features like client-side load balancing, a pluggable name resolution mechanism and automatic retries. * A flexible interceptor layer allowing you to implement cross-cutting logic like authentication, logging, and metrics. ## Hello, swift.org! Consider the canonical “hello world” service with a single API which returns a greeting. You might define it like this in a `.proto` file: syntax = "proto3"; service GreetingService { // Returns a personalized greeting. rpc SayHello(SayHelloRequest) returns (SayHelloResponse); } message SayHelloRequest { // The name of the person to greet. string name = 1; } message SayHelloResponse { // The personalized greeting message. string message = 1; } gRPC can be configured to generate: * Service code so you can implement the business logic. * Client code to make requests against the service. Code for messages is generated by SwiftProtobuf and used in conjunction with the generated gRPC code. ### Generated Service Code The generated code includes a Swift protocol describing the requirements of the service with one method for each `rpc` in the service definition. To implement the business logic of your service just implement one of the service protocols. The example below uses the `SimpleServiceProtocol` which is the highest level API. If you need more flexibility you can use the `ServiceProtocol` or `StreamingServiceProtocol` which trade off conciseness for flexibility. To start the service you need to create a server configured to use a transport and an instance of your service: import GRPCCore import GRPCNIOTransportHTTP2 struct Greeter: GreetingService.SimpleServiceProtocol { func sayHello( request: SayHelloRequest, context: ServerContext ) async throws -> SayHelloResponse { return SayHelloResponse.with { $0.message = "Hello, \(request.name)!" } } } @main struct GreeterServer { static func main() async throws { // Create a plaintext server using the SwiftNIO based HTTP/2 transport // listening on 128.0.0.1:8080. let server = GRPCServer( transport: .http2NIOPosix( address: .ipv4(host: "127.0.0.1", port: 8080), transportSecurity: .plaintext ), services: [Greeter()] ) // Start serving indefinitely. try await server.serve() } } ### Generated Client Code gRPC generates an idiomatic client for you, simplifying service calls. To use it, first create a raw client and wrap it with the generated client specific to your service. This generated client provides a type-safe way for you to easily interact with your service. import GRPCCore import GRPCNIOTransportHTTP2 @main struct SayHello { static func main() async throws { // Create a plaintext client using the SwiftNIO based HTTP/2 transport // connecting to a service listening on 128.0.0.1:8080. try await withGRPCClient( transport: .http2NIOPosix( target: .dns(host: "127.0.0.1", port: 8080), transportSecurity: .plaintext ) ) { client in let greeter = GreetingService.Client(wrapping: client) let greeting = try await greeter.sayHello(.with { $0.name = "swift.org" }) print(greeting.message) } } } ## Package Ecosystem gRPC Swift 2 was designed with flexibility in mind. It’s distributed as a collection of packages, allowing you to pick and choose the components which best suit your needs. These features are provided by the following packages: * grpc/grpc-swift-2 provides runtime abstractions and types. * grpc/grpc-swift-nio-transport implements client and server transports using HTTP/2 and is built on top of SwiftNIO. * grpc/grpc-swift-protobuf integrates with SwiftProtobuf to provide a code generator for services defined in `.proto` files. * grpc/grpc-swift-extras includes common gRPC add-ons, like the reflection and health services, integrations with Swift Service Lifecycle, and interceptors to trace RPCs using OpenTelemetry. ## Next Steps To get started with gRPC Swift 2 check out the tutorials and documentation which are hosted on the Swift Package Index, or try out one of the examples in the grpc/grpc-swift-2 repository. If you have feature requests, want to report a bug, or would like to contribute to the project then please reach out to us on GitHub or join us on the Swift forums. Let’s connect!
01.08.2025 08:08 — 👍 0    🔁 0    💬 0    📌 0
Updating the Visual Studio Code extension for Swift Today, we are excited to announce a new version of the Swift extension for Visual Studio Code – now published to the extension marketplace as an official supported release of the Swift team. The aim of this extension is to provide a high-quality, feature-complete extension that makes developing Swift applications on all platforms a seamless experience. As we continue to invest in Swift as a first-class language for cross-platform development, both Apple and the broader developer community are rapidly iterating on the VS Code extension to expand its capabilities for server and cloud, embedded, and Linux and Windows app development. The original extension was developed by members of the Swift Server Working Group, and with its broader scope, they have graciously supported this transition to the GitHub /swiftlang organization and the creation of a new publisher for the extension. For existing Swift developers using VS Code, the transition should be seamless: the old release should automatically install the new extension and disable itself, and moving forward all language features will be provided by the new extension. You’re welcome to uninstall the original extension, which has been renamed to reflect its deprecated status. Further details about the migration can be found on the Swift Forums. If you have any issues migrating, please file an issue or comment on the forum post.
01.08.2025 08:08 — 👍 0    🔁 0    💬 0    📌 0
Introducing swiftly 1.0 Today we’re delighted to introduce the first stable release of swiftly, a Swift version manager that takes the pain out of installing, managing and updating your Swift toolchain. The latest version of Swift is bundled with Xcode for writing apps for Apple platforms. But perhaps you want to install Swift on a different platform like Linux, or use a different version of the toolchain for building services or command line tools. Downloading, extracting and installing a trusted build of Swift along with the relevant dependencies for your operating system can require quite a few manual and error-prone steps. swiftly has been around for some years as a community-supported tool for Swift developers using Linux. With this release, we’re officially supporting it as part of the core Swift toolchain, including hosting it as part of the Swift GitHub organization. We’ve also added macOS support to make it easier to install Swift separately from Xcode. ## Introducing swiftly swiftly is the best tool to install the standalone toolchain, providing commands to install Swift on a new system, update to the latest stable version, and experiment or test with nightly snapshots or older versions. It also makes it easy to switch effortlessly between multiple installed toolchains. You can even add a file to your project repository so swiftly will use the same toolchain version for all members of your development team. Naturally, swiftly itself is written in Swift, and is able to update itself to the latest version. ## Quick tour Let’s take a look at some of the features of swiftly! To get started, visit swift.org/install and install it. swiftly will provide directions after installation if there are any system packages, or shell commands needed for smooth operation of the new toolchain. The latest Swift toolchain is installed as the default, so you can immediately use it to start a new project. For example: $ swift package init The `swiftly use` command selects the default toolchain for Swift commands (e.g. `swift test`, `swift build`): $ swiftly use 6.0.3 $ swift --version -- Apple Swift version 6.0.3 (swiftlang-6.0.3.1.2 clang-1600.0.28.6) Target: arm64-apple-macosx15.0 At a later point, if there’s a new release of Swift you can install it alongside the existing toolchain with the `latest` command: $ swiftly install latest Pre-release of versions of Swift are available, including nightly “snapshot” toolchains. They can be easily listed using swiftly: $ swiftly list-available main-snapshot -- Available main development snapshot toolchains ---------------------------------------------- main-snapshot-2025-03-25 ... Once you’ve identified a snapshot toolchain, it can be installed using its name: $ swiftly install main-snapshot-2025-03-25 -- Installing main-snapshot-2025-03-25 Another way to temporarily use a specific version of Swift is to use the special ‘+’ selector. With this syntax, you don’t need to first switch to a different toolchain: $ swiftly run lldb +main-snapshot-2025-03-25 -- (lldb) _ If you’re building a SwiftPM project in a team setting and want to enforce a common version of the Swift toolchain on all contributors, simply create a `.swift-version` file in the root of your project folder with the desired version (e.g. “6.0.3”). As swiftly is updated with new features and bug fixes, you can run `swiftly self-update` to check and install new releases. ## How swiftly works By writing swiftly in Swift, we’re able to take advantage of the language’s features, support, and ecosystem of related projects. Swift comes with standard library features for working with the filesystem in its Foundation module. For network operations Async HTTP Client is there to work the HTTP requests. And to retrieve the latest Swift release, swiftly uses the Swift OpenAPI plugin to generate the code to interact with the swift.org website. Lastly, it takes advantage of Swift’s interoperability with C to use the existing libarchive library to work with archives. swiftly uses libarchive to extract the toolchains downloaded from the Swift website and the integration is simple. It can be challenging to build shell programs that work well across multiple platforms with minimal system dependencies; this motivated us to switch swiftly away from using a shell program to install it and become a self-installing binary application. swiftly has access to excellent argument parsing capabilities, beautiful `--help` screens, and the full standard library. The only remaining problem was being able to deliver the operating system and processor architecture specific binary to the users system with simplicity. The swift.org website helps with operating system detection, but it cannot reliably detect the Linux distribution. Luckily, there is the Swift Static Linux SDK that makes binaries that work with a wide range of distributions. The processor architecture can be determined on most unixes using `uname -m` . The result of all of this is the simplicity of a copy and paste from the website to your terminal and get started with Swift. ## Installing Swift, swiftly Moving forward, swiftly will become the default way to install Swift outside of Xcode. The initial version supports macOS and a variety of Linux distributions, including Ubuntu, Debian, Fedora, Red Hat Enterprise Linux and Amazon Linux. The swiftly documentation provides further information about using swiftly in a CI/CD environment, as well as setting proxy servers and custom install locations for enterprise environments. swiftly is an open source project, and so you can raise new issues or contribute pull requests at its GitHub repository. You can also ask questions or discuss swiftly on the Swift Forums. Special thanks to Patrick Freed for creating swiftly, contributing it to the Swift organization, and his continued contributions to this valuable tool. The community is what makes Swift amazing!
01.08.2025 08:08 — 👍 0    🔁 0    💬 0    📌 0
Swift 6.1 Released Swift 6.1 is now available! This release includes new language enhancements to improve productivity, diagnostics improvements, package traits, and ongoing work to improve data-race safety usability and compile times. Read on for an overview of the changes to the language, package manager, and next steps for getting started with Swift 6.1. ## Language and Standard Library ### Concurrency Swift’s concurrency model allows writing `nonisolated` on properties and functions to indicate that an API is safe to call from any concurrent context. Swift 6.1 extends `nonisolated` to types and extensions. This allows you to write `nonisolated` to prevent `@MainActor` inference on a type, or to apply `nonisolated` to all methods in an extension without having to annotate every method: @MainActor struct S { let id: Int let name: String // mutable state and MainActor methods } nonisolated extension S: CustomStringConvertible, Equatable { var description: String { "id: \(id), name: \(name)" } static func ==(lhs: S, rhs: S) -> Bool { lhs.id == rhs.id } } Swift 6.1 also improves type inference for task groups by inferring the child task result type of `withTaskGroup` and `withThrowingTaskGroup`. Previously, you always had to write the child task result type as an argument when creating the task group: let messages = await withTaskGroup(of: Message.self) { group in for id in ids { group.addTask { await downloadMessage(for: id) } } var messages: [Message] = [] for await message in group { messages.append(message) } return messages } In Swift 6.1, the child task result type can be inferred from the task group closure: // No need for `(of: Message.self)` like before. let messages = await withTaskGroup { group in for id in ids { group.addTask { await downloadMessage(for: id) } } var messages: [Message] = [] for await message in group { messages.append(message) } return messages } The approachability of data-race safety remains an area of active development; you can find an overview of the approach in the vision document for improving the approachability of data-race safety. Many Swift Evolution proposals implementing the features described in the vision document are under active review, and your feedback will help shape these improvements. ### Implementing Objective-C types in Swift Swift 6.1 includes a new attribute, `@implementation`, which can be used together with `@objc` to provide an implementation for a declaration that has been imported from Objective-C. You can write `@objc @implementation` on a Swift `extension` to replace an Objective-C `@implementation` block. You write headers as normal for an Objective-C class, but instead of writing an `@implementation` in an Objective-C file, you write an `@objc @implementation extension` in a Swift file. You can even port an existing class’s implementation to Swift one category at a time without breaking backwards compatibility. ### Productivity enhancements Swift allows including trailing commas in collection literals to make it easy to append, remove, reorder, or comment out the last element as any other element: let rank = [ "Player 1", "Player 3", "Player 2", ] Swift 6.1 extends trailing comma support to tuples, parameter and argument lists, generic parameter lists, closure capture lists, and string interpolations: let numbers = [1, 2, 0, 3, 4, 0, 0, 5] let subsequences = numbers.split( separator: 0, maxSplits: 1, ) In addition to improved development ergonomics, code generation tools like plugins and macros can be simplified, because generating a comma-separated list no longer needs a special condition for the last element. You can find a complete list of language proposals that were accepted through the Swift Evolution process and implemented in Swift 6 on the Swift Evolution dashboard. ## Package and build improvements Swift 6.1 introduces _package traits_ , a new configuration for packages that allows them to offer different APIs and features when used in specific environments, such as Embedded Swift and WebAssembly. Package authors can define a set of traits in their `Package.swift` that their package offers, which provide a way to express conditional compilation and optional dependencies. The package can specify a set of default traits that are enabled in clients, and clients can customize the traits they use when they declare the dependency: dependencies: [ .package( url: "https://github.com/Org/SomePackage.git", from: "1.0.0", traits: [ .default, // enable all of the package's default traits "Embedded" ] ), ] Many editing features, such as jump to definition for APIs in libraries you’re using, are powered by indexing. Before Swift 6.1, indexing occurred when you built your project, which meant that any additions or changes to the library were only surfaced by those editing features after you perform a build. Swift 6.1 enables background indexing by default for SwiftPM projects in SourceKit-LSP. Cross-module and global functionality stays updated as you make changes to your project. ## Swift Testing Swift 6.1 enables custom Swift Testing traits to perform logic before or after tests run in order to share set-up or tear-down logic. If you write a custom trait type which conforms to the new `TestScoping` protocol, you can implement a method to customize the scope in which each test or suite the trait is applied to will execute. For example, you could implement a trait which binds a task local value to a mocked resource: struct MockAPICredentialsTrait: TestTrait, TestScoping { func provideScope(for test: Test, testCase: Test.Case?, performing function: @Sendable () async throws -> Void) async throws { let mockCredentials = APICredentials(apiKey: "fake") try await APICredentials.$current.withValue(mockCredentials) { try await function() } } } extension Trait where Self == MockAPICredentialsTrait { static var mockAPICredentials: Self { Self() } } @Test(.mockAPICredentials) func example() { // Validate API usage, referencing `APICredentials.current`... } For more details, see ST-0007: Test Scoping Traits. Swift Testing in Swift 6.1 also includes refined versions of the `#expect(throws:)` and `#require(throws:)` macros which return their caught errors, making inspecting them in test functions more ergonomic (ST-0006). ## Swift-DocC Swift-DocC introduces a more human readable and human writable alternative for symbol link disambiguation based on parameter type and return type information. For example, consider these three function overloads with different parameter types and return types: func doSomething(first: String, second: Int) -> Double func doSomething(first: String?, second: Int) -> Float func doSomething(first: String?, second: Int) -> Double Previously, if you wrote a link to one of these overloads you needed to include a short hash of that symbol’s unique identifier to disambiguate the link and uniquely reference the specific overload. Swift-DocC’s warnings aided in writing these hashes but a person can’t decode the resulting hash suffix (`-3c5j`) to determine which overload the link is referring to. Now, you can use a combination of parameter types and return types—like `-(String,_)`, `->Float,` or `-(String?,_)->Double`—to disambiguate the link and uniquely reference a specific overload. You can discover the minimal combination of parameter types and return types for each overload from Swift-DocC’s warnings about ambiguous symbol links. For more details, see the Ambiguous Symbol Links section of Linking to Symbols and Other Content. ## Install Swift 6.1 You can try out these exciting new developments in Swift 6.1 today! If you’re building apps for Apple platforms, Swift 6.1 is included in Xcode 16.3, now available from the App Store. And the easiest way to install the standalone Swift 6.1 toolchain is using swiftly, the new Swift version manager that runs on macOS and Linux. Additional installation methods, including for Windows, are included on the Install Swift page.
01.08.2025 08:08 — 👍 0    🔁 0    💬 0    📌 0
Swift at Apple: Migrating the Password Monitoring service from Java _Swift is heavily used in production for building cloud services at Apple, with incredible results. Last year, the Password Monitoring service was rewritten in Swift, handling multiple billions of requests per day from devices all over the world. In comparison with the previous Java service, the updated backend delivers a 40% increase in performance, along with improved scalability, security, and availability._ The Passwords app, introduced in the fall of 2024, helps users manage their passwords, passkeys, and verification codes. It allows them to store, autofill, and generate strong passwords that can be shared across all their devices, as well as share passwords with trusted contacts. One security feature included in the app is Password Monitoring, which warns users if one of their saved passwords shows up in a data leak. This feature has a server component, running on Linux-based infrastructure, that is maintained by Apple. On a regular interval, Password Monitoring checks a user’s passwords against a continuously updated and curated list of passwords that are known to have been exposed in a leak. Importantly, this task is handled in a thoughtful, privacy-preserving way that never reveals users’ passwords to Apple. A detailed discussion of how this is done using the cryptographic private set intersection protocol is in the Password Monitoring section of the Apple Platform Security guide. The migration from Java to Swift was motivated by a need to scale the Password Monitoring service in a performant way. The layered encryption module used by Password Monitoring requires a significant amount of computation for each request, yet the overall service needs to respond quickly even when under high load. ## Choosing Swift for increased performance For years, our team relied on Java to power large-scale, mission-critical services because of its proven stability and performance. However, Java’s memory management approach no longer aligns with our growing demands and efficiency goals. Instead of simply expanding hardware resources, we were seeking a more-efficient language to support our growth while reducing server overhead. Prior to seeking a replacement language, we sought ways of tuning the JVM to achieve the performance required. Java’s G1 Garbage Collector (GC) mitigated some limitations of earlier collectors by introducing features like predictable pause times, region-based collection, and concurrent processing. However, even with these advancements, managing garbage collection at scale remains a challenge due to issues like prolonged GC pauses under high loads, increased performance overhead, and the complexity of fine-tuning for diverse workloads. One of the challenges faced by our Java service was its inability to quickly provision and decommission instances due to the overhead of the JVM. The Password Monitoring service runs globally, so service load can greatly fluctuate throughout the day, even with client-side techniques to smooth over the distribution of traffic. The peak and trough of a day differ by approximately 50% regionally. To efficiently manage this, we aim to scale down when demand is low and scale up as demand peaks in different regions. A faster bootstrap time is a crucial requirement to support this dynamic scaling strategy. Given the scale of our application and the volume of traffic we manage daily, the decision to transition from Java to another language was not made lightly. We evaluated our options, and found only a few languages that could help us achieve our goals. While you might expect that Apple would automatically choose Swift, we were pleasantly surprised by how well it fit the unique needs of a cloud-based service like ours. Swift has expressive syntax that was easy to learn, and could deliver the performance improvements necessary to meet the demands of our compute workloads. We decided to take a significant leap and started a rewrite of the Password Monitoring backend using Swift. ## Our experience developing with Swift We began rewriting our service using Vapor, a Swift web framework that provided Routing, Controller, and Content modules that we were able to build upon. Our service had additional requirements that led us to create a few custom packages with essential functionality: elliptic curve operations that are crucial for implementing password monitoring, auditing, configuration, error handling, and custom middleware. One of the most significant aspects of Swift that impressed us was its emphasis on protocols. In Java, we relied heavily on inheritance, which can lead to complex class hierarchies and tight coupling. Swift’s approach of protocols and generics promotes modularity and reusability by allowing classes, structs, and enums to share common protocols, enabling a more flexible and scalable codebase. This shift in mindset encouraged us to think in terms of behaviors rather than concrete classes, resulting in cleaner and more maintainable code. Safety is another area where Swift takes a distinctive approach compared to Java. For example, Swift’s optional type and safe unwrapping mechanisms eliminate the need for null checks everywhere, reducing the risk of null pointer exceptions and enhancing code readability. This safety-first approach ingrained throughout Swift’s language design, whether it is deterministic deallocation, copy-on-write (CoW), or value types, makes it inherently less prone to runtime errors. Swift’s async/await support is a nice addition, streamlining how we handle async tasks. Previously, managing async operations often involved complex callback patterns or external libraries. Swift’s async/await syntax simplifies this process, making it more intuitive and less error-prone. We can now write async code that reads like sync code, leading to more readable, testable, and maintainable concurrency handling—especially critical in high-load, multi-threaded environments. Overall, our experience with Swift has been overwhelmingly positive and we were able to finish the rewrite much faster than initially estimated. Swift allowed us to write smaller, less verbose, and more expressive codebases (close to 85% reduction in lines of code) that are highly readable while prioritizing safety and efficiency. Our service benefited from a diverse ecosystem of Swift packages, including logging frameworks, a Cassandra client, and crypto libraries that were readily available. In addition to an excellent support system and tooling, Swift’s inherent emphasis on modularity and extensibility helped future-proof and simplify the integration and customizations needed for our service-specific functions. ## Takeaways for future Swift on server development We benchmarked performance throughout the process of development and deployment, allowing us to discover the trait of the Swift programming language that delighted us the most — its efficiency. Swift’s deterministic memory management led to a much lower memory threshold for our service. Not only were our initial results heartening, but after a few iterations of performance improvements, we had close to 40% throughput gain with latencies under 1 ms for 99.9% of requests on our current production hardware. Additionally, the new service had a much smaller memory footprint per instance — in the 100s of megabytes — an order of magnitude smaller compared to the 10s of gigabytes our Java implementation needed under peak load to sustain the same throughput and latencies. The service runs on Kubernetes, and the migration’s efficiency improvements allowed us to release about 50% of its capacity for other workloads. Our Swift implementation has run smoothly and efficiently in production, making it worth the effort we put into this migration. In addition to outperforming our previous Java-based application, Swift delivered better performance consistency, enhanced safety features, and robust reliability — all while requiring fewer resources by utilizing memory and CPU efficiently. With fewer lines of boilerplate code and more flexible design patterns that we used, we look forward to simplified maintenance of our application. Swift was a powerful choice for building fast, resilient, and maintainable applications in our high-demand environment.
01.08.2025 08:08 — 👍 0    🔁 0    💬 0    📌 0
ICYMI: Memory Safety, Ecosystem Talks, and Java Interoperability at FOSDEM 2025 The Swift community had a strong presence at FOSDEM 2025, the world’s largest independently run open source conference, held every year in Brussels, Belgium. FOSDEM highlighted a range of Swift-related talks related to memory safety, a broad ecosystem around Swift including using it to develop web services and embedded projects, and new areas of the project including Java interoperability. In case you missed it, here are a few highlights from the event: ## Memory Safety in Swift The main track of the conference featured a talk presented by Doug Gregor on memory safety: “Incremental Memory Safety in an Established Software Stack: Lessons Learned from Swift.” If you’re interested in learning more about Swift’s memory safe features, this talk is a great place to start; it walks through the different dimensions of memory safety in Swift, the language’s safe interoperability with C(++), and reflects on lessons learned for both programming language design and adopting Swift in an established software codebase. To learn more about memory safety in Swift, see the Swift documentation page on memory safety, as well as the vision document on memory safety. ## Swift DevRoom FOSDEM is primarily organized into DevRooms, volunteer-organized conference tracks around technical communities and topics. This year Swift celebrated its inaugural DevRoom organized by a local community member, Steven Van Impe, with contributions from a large group of volunteers including proposal reviewers, speakers, and day-of-operations support. Swift’s first Swift DevRoom was a hit! 🎉 The room was packed with 12 talks, covering a wide range of topics and demos from the Swift ecosystem: talks related to running Swift on Linux, showcasing various IDEs like VS Code, and a whole hour dedicated to embedded content. A few talks to highlight from the event: * Building a Ferrofluidic Music Visualizer with Embedded Swift * Building container images with swift-container-plugin * Distributed Tracing in Server-Side Swift Check out the complete lineup to learn more! ## Java Interoperability In the Free Java DevRoom, Konrad ‘ktoso’ Malawski presented on Java interoperability in Swift: “Foreign Function and Memory APIs and Swift/Java interoperability.“ Konrad’s talk was a technical deep dive into the Java interoperability effort that launched in 2024, demonstrating the bridges and bindings needed to integrate systems written in Swift and Java while still maintaining great performance. Catch up on this talk to see how you can leverage existing libraries without complete rewrites. Work in early development has been released on GitHub for feedback and contributions, and your feedback is welcome on the forums.
01.08.2025 08:08 — 👍 0    🔁 0    💬 0    📌 0
Redesigned Swift.org is now live Over the past few months, the website workgroup has been redesigning Swift.org. On behalf of the website workgroup, I’m pleased to announce that we have merged the initial changes. Our goal with the site redesign has been to make Swift.org more approachable for newcomers to Swift, highlight the language’s technical strengths, and make it easy to get started. That led to a focus on the website’s appearance, improving the user experience, and emphasizing important features such as Swift’s multiplatform support. Today’s release includes refreshed home and install pages. Additionally, new pages have been designed to explore Swift use cases, including cloud services, command line tools, and embedded software. Looking forward, we plan to take an iterative approach to improving the website, including pushing changes live as we complete their design and implementation. ## Brand new design We explored several design options and found that the latest design conveys the fluidity and creativity of Swift through the splash of orange and the bird animation in the background. ## Curated content and examples The homepage now highlights Swift’s strengths alongside code examples that illustrate them. Additionally, we showcase various types of software that can be developed using Swift; these new use case pages provide information such as relevant packages, examples of Swift in action, code snippets, and links to resources for further learning. ## Next Steps We look forward to hearing your feedback on this first set of changes as we continue to redesign other sections of the site. There are several ways to offer feedback on the redesign and to get involved: * A forum announcement has been shared on the forums that can be used for discussion, and the website repository has GitHub issues. * The website itself is open source, and your contributions to the swiftlang/swift-org-website repository are welcome. * The Swift Information Architecture Project is an ongoing effort that has helped inform decisions related to the site redesign. Thank you to the website workgroup and community members for contributing to these improvements.
01.08.2025 08:08 — 👍 0    🔁 0    💬 0    📌 0
Announcing Swift 6 We’re delighted to announce the general availability of Swift 6. This is a major new release that expands Swift to more platforms and domains. Many people know of Swift as a language for app development, with a million apps on the App Store. But Swift is great for more than just apps. Swift’s safety, speed, and approachability make it a great choice for many other use cases including libraries, internet-scale services, and the most performance-critical and secure code. Swift 6 scales even further through new low-level programming features, an embedded Swift language subset, expanded Linux and Windows support, new cross-platform APIs including the new Swift Testing library, and more. Read on for a deep dive into changes to the language, standard libraries, debugging, platform support, and next steps for getting started with Swift 6. ## Language and Standard Library ### Concurrency Swift has long offered memory safety, ensuring that variables are initialized before they’re used, memory isn’t accessed after it’s been deallocated, and array indices are checked for out-of-bounds errors. Swift 6 now includes a new, opt-in language mode that extends Swift’s safety guarantees to prevent data races in concurrent code by diagnosing potential data races in your code as compiler errors. Data-race safety checks were previously available as warnings in Swift 5.10 through the `-strict-concurrency=complete` compiler flag. Thanks to improved `Sendable` inference and new compiler analysis for transferring mutable state from one actor to another, Swift 6 warnings about data-race safety have fewer false positives. You can find more information about the Swift 6 language mode and how to migrate at Swift.org/migration. Swift 6 marks the start of the journey to make data-race safety dramatically easier. The usability of data-race safety remains an area of active development, and your feedback will help shape future improvements. Swift 6 also comes with a new Synchronization library for low-level concurrency APIs, including atomic operations and a new mutex API. ### Typed throws Swift 6 enables functions to specify the type of error that they throw as part of their signature. This feature is useful in generic code that forwards along errors thrown in client code, or in resource-constrained environments that cannot allocate memory, such as in embedded Swift code. For example: func parseRecord(from string: String) throws(ParseError) -> Record { // ... } A call to `parseRecord(from:)` will either return a `Record` instance or throw an error of type `ParseError`. A `do..catch` block will infer `ParseError` as the type of the `error` variable: do { let record = try parseRecord(from: myString) } catch { // 'error' has type 'ParseError' } Typed throws generalizes over throwing and non-throwing functions. A function that is specified as `throws` (without a specific error type) is equivalent to one that specifies `throws(any Error)`, whereas a non-throwing function is equivalent to one that specifies `throws(Never)`. Calls to functions that are `throws(Never)` are non-throwing and don’t require error handling at the call site. Typed throws can also be used in generic functions to propagate error types from parameters, in a manner that is more precise than `rethrows`. For example, the `Sequence.map` method can propagate the thrown error type from its closure parameter, indicating that it only throws the same type of errors as the closure: extension Sequence { func map<T, E>(_ body: (Element) throws(E) -> T) throws(E) -> [T] { // ... } } When given a closure that throws `ParseError`, `map` will throw `ParseError`. When given a non-throwing closure, `E` is inferred to `Never` and `map` will not throw. ### Ownership Swift 5.9 introduced non-copyable types with the `~Copyable` syntax for modeling resources with unique ownership, and writing performance-conscious code by eliminating the runtime overhead associated with copying. Swift 6 now supports these types with the generics system, making it possible to write generic code that works with both copyable and non-copyable types. For example: protocol Drinkable: ~Copyable { consuming func use() } struct Coffee: Drinkable, ~Copyable { /* ... */ } struct Water: Drinkable { /* ... */ } func drink(item: consuming some Drinkable & ~Copyable) { item.use() } drink(item: Coffee()) drink(item: Water()) The `Drinkable` protocol has no requirement that its conforming types are `Copyable`. This means both the non-copyable type `Coffee` and copyable type `Water` can be passed into the generic `drink` function. Switch statements can now be written to avoid copying within enum pattern-matching operations. This means that switch statements can be used with non-copyable payloads and can also provide performance benefits for copyable payloads, especially those based on copy-on-write containers like `Array` and `Dictionary`. Non-copyable types are already used throughout the standard libraries. For instance, the new `Atomic` type in the Synchronization library is based on `~Copyable`, `Optional` and `Result` can now wrap non-copyable types, and the unsafe buffer pointer types can now point to non-copyable elements. C++ interoperability also uses non-copyable types to expose C++ move-only types to Swift. ### C++ interoperability Swift 5.9 introduced bidirectional interoperability with C++ to seamlessly bring Swift to more existing projects. Swift 6 expands interoperability support to C++ move-only types, virtual methods, default arguments, and more standard library types including `std::map` and `std::optional`. C++ types that do not have a copy constructor can now be accessed from Swift 6 as non-copyable types with `~Copyable`. And for those times when it’s useful to expose a C++ type with a copy constructor as `~Copyable` in Swift for better performance, a new `SWIFT_NONCOPYABLE` annotation can be applied to the C++ type. Swift now also supports calls of C++ virtual methods on types annotated as `SWIFT_SHARED_REFERENCE` or `SWIFT_IMMORTAL_REFERENCE`. When calling C++ functions or methods that have default argument values for some of their parameters, Swift now respects these default values, rather than requiring you to explicitly pass an argument. ### Embedded Swift Swift 6 includes a preview of Embedded Swift, a language subset and compilation mode suitable for embedded software development, such as programming microcontrollers. The toolchain supports ARM and RISC-V bare-metal targets. Embedded Swift produces small and standalone binaries by relying on generic specialization. Since it doesn’t rely on a runtime or type metadata, Embedded Swift is suitable for platforms with tight memory constraints as well as use in low-level environments with limited runtime dependencies. Embedded Swift remains an experimental feature, with ongoing development before stable support in a future Swift release. ### 128-bit Integers Swift 6 rounds out the set of low-level integer primitives with the addition of signed and unsigned 128-bit integer types. These are available on all Swift platforms, and provide the same API as other fixed-width integer types in the standard library. ### Productivity enhancements Swift 6 introduces a number of productivity enhancements, including `count(where:)` to streamline counting the number of elements in a sequence that satisfy a predicate, pack iteration for writing natural `for`-loops over the elements in a value parameter pack, access control for imports to keep implementation details from leaking into your public APIs, `@attached(body)` macros for synthesizing and augmenting function implementations, expression macros as default arguments, and more. You can find a complete list of language proposals that were accepted through the Swift Evolution process and implemented in Swift 6 on the Swift Evolution dashboard. ## Debugging ### Custom LLDB summaries with `@DebugDescription` @DebugDescription` section" href="#custom-lldb-summaries-with-debugdescription"> Swift 6 provides a new debugging macro to easily customize how an object is displayed in LLDB when using the `p` command, and in the variables view in Xcode and VSCode, by using a formatting scheme that does not run arbitrary code. Types that conform to `CustomDebugStringConvertible` provide a `debugDescription` property that returns a string describing the object. In LLDB, the `po` command calls this computed property on an object. In contrast, the `p` command uses LLDB’s type summary formatters to directly format the object using its stored property values. `@DebugDescription` is a new macro in the standard library which lets you specify LLDB type summaries for your own types directly in code. The macro processes the `debugDescription` property, translating simple string interpolations involving stored properties into LLDB type summaries. This allows LLDB to use your custom formatting even when using `p`, and also in Xcode or VSCode’s variable display windows. The macro can use an existing conformance to `CustomDebugStringConvertible`, or you can provide a separate string interpolation only for use in LLDB’s `p` command. Providing a separate LLDB description string is useful if your `CustomDebugStringConvertible` implementation doesn’t meet the requirements of the `@DebugDescription` macro, or if you’re familiar with the LLDB Summary String syntax and you want to use it directly. For example, the following code customizes how `po` in LLDB displays the `Organization` type with a conformance to `CustomDebugStringConvertible`, and the `@DebugDescription` macro exposes this custom formatting to the `p` command and the variables view: @DebugDescription struct Organization: CustomDebugStringConvertible { var id: String var name: String var manager: Person // ... and more var debugDescription: String { "#\(id) \(name) [\(manager.name)]" } } (lldb) p myOrg (Organization) myOrg = "`#100 Worldwide Travel [Jonathan Swift]`" ### Improved startup performance with explicit modules Swift 6 dramatically improves startup performance in the debugger when you use explicit module builds. When debugging locally-built code, LLDB can now import explicitly-built Swift and Clang modules directly from the project build artifacts. This avoids the need to recompile implicit Clang module dependencies from source, which can take a long time, and it’s very sensitive to issues with header search paths. If the first `p` or `po` command in LLDB takes a long time due to Clang module compilation, or if your debugging is frequently blocked by Clang header import problems, consider adopting explicit modules in your project! ## Libraries ### Foundation Swift 6 unifies the implementation of Foundation across all platforms. The modern, portable Swift implementation provides consistency across platforms, it’s more robust, and it’s open source. macOS and iOS started using the Swift implementation of Foundation alongside Swift 5.9, and Swift 6 brings these improvements to Linux and Windows. Core types like `JSONDecoder`, `URL`, `Calendar`, `FileManager`, `ProcessInfo`, and more have been completely reimplemented in Swift. These types share their implementation with macOS 15 and iOS 18, providing a new level of cross-platform consistency, reliability, and performance. Recently released APIs like `FormatStyle`, `ParseStrategy`, `Predicate`, and `JSON5`, from past macOS and iOS releases are now available on all Swift platforms. New Foundation APIs like `Expression`, calendar enumeration improvements, calendar recurrence rules, format style enhancements, and more are available simultaneously on macOS, iOS, Linux, and Windows - and they were built with community involvement. If your Linux or Windows app imports the `Foundation` library from the Swift toolchain today, you get all of these improvements for free. And if your app is particularly sensitive to binary size, you can now import the `FoundationEssentials` library, which provides a more targeted subset of Foundation’s features that omits internationalization and localization data. ### Swift Testing Swift 6 introduces Swift Testing, a new testing library designed from the ground up for Swift. It includes expressive APIs that make it easy to write and organize tests. It provides detailed output when a test fails using macros like `#expect`. And it scales to large codebases with features like parameterization to easily repeat a test with different arguments. For example: @Test("Continents mentioned in videos", arguments: [ "A Beach", "By the Lake", "Camping in the Woods" ]) func mentionedContinents(videoName: String) async throws { let videoLibrary = try await VideoLibrary() let video = try #require(await videoLibrary.video(named: videoName)) #expect(video.mentionedContinents.count <= 3) } Swift Testing takes full advantage of macros. Its `@Test` and `@Suite` attached macros declare test functions and suite types respectively, and they accept arguments (known as traits) to customize various behaviors. The `#expect` and `#require` expression macros validate expected behaviors, and capture rich representation of expressions and their sub-values to produce detailed failure messages. Since Swift Testing is included directly in Swift 6 toolchains, you can `import Testing` without needing to declare a package dependency. This means your tests do not need to build Swift Testing or its dependencies (including swift-syntax), and its macro implementation comes prebuilt. The package manager in Swift 6 automatically builds and runs Swift Testing tests in addition to XCTests (if present), and shows results from both libraries in log output. Swift Testing supports all platforms that Swift officially supports, including all Apple platforms, Linux, and Windows. To learn more about this new open source project, visit the swift-testing repository on GitHub, and get involved with its ongoing development on the forums. ## Platform Support Swift is designed to support development and execution on all major operating systems, and platform consistency and expansion underpins Swift’s ability to reach new programming domains. Swift 6 brings major improvements to Linux and Windows across the board, including support for more Linux distributions and Windows architectures. Toolchains for all of the following platforms are available for download from Swift.org/install. ### Fully static SDK for Linux Swift 6 supports building fully statically linked executables for Linux; these have no external dependencies, so they are ideal for situations where you want to copy a program directly onto a system or into a container and run it without installing any extra software. The SDK can also be used to cross-compile to Linux from other platforms. Learn how to get started with the static SDK for Linux on Swift.org. ### New Linux distributions Swift 6 adds official support and testing for Debian and Fedora, as well as on Ubuntu 24.04. ### Windows build performance Prebuilt toolchains are now available for the arm64 architecture, which provides improved compiler performance for Windows on ARM hosts. In Swift 6, the Swift package manager also parallelizes builds across multiple cores on Windows by default. On a 10-core machine, this can improve build performance by up to a factor of 10! ## Next Steps ### Download Swift 6 You can try out these exciting new developments in Swift 6 today! Install the official Swift 6 toolchains for macOS, Linux, and Windows at Swift.org/install. ### Get started with Swift The Swift Programming Language book has been updated to reflect the latest Swift 6 syntax and features. It serves as the official Swift guide and an excellent starting point for learning the language. To help kickstart your Swift journey, Swift.org/getting-started offers tutorials for various use cases, including building a cross-platform library, a web service using Vapor, and an embedded application for a microcontroller. There are also articles for diving deeper into some of Swift’s most popular features. ### Explore the package ecosystem The Swift package ecosystem is continuously growing with new technologies to help you with a variety of tasks in your projects. You can explore package highlights at Swift.org/packages, which features popular package categories and a selection of new and notable packages that are hand-curated from an open nomination process every month. ### Get involved Your experience with Swift 6 and your feedback can help shape the future evolution of the language, the tools, the package ecosystem, and the community. You can get involved by sharing your packages, documentation improvements, educational content, bug reports and enhancement requests, code contributions, and participating in forum discussions. Learn more at Swift.org/contributing. Swift 6 is the culmination of countless contributions from members across the Swift community, and it marks a decade of building this incredible language, ecosystem, and community together. Thank you to everyone who participated in development and provided feedback. Your contributions make Swift a better language.
30.07.2025 04:08 — 👍 1    🔁 1    💬 0    📌 0