Unlocking Efficiency with Noncopyable Structs and Enums in Swift 5.9

Saeid Rezaeisadrabadi
2 min readMar 18, 2024

--

In this story, I want to talk about a new feature in Swift 5.9. noncopyable structs and enums. This feature allows you to create types that act more like unique entities, similar to classes, but with the inherent efficiency and value semantics of structs and enums. Let’s dive into this exciting addition and explore its potential!

What are Noncopyable Structs and Enums?

Traditionally, structs and enums are inherently copyable. When you pass them around, a new copy is created. However, this simplicity comes at a cost: unnecessary memory allocations and potential performance overhead. Enter noncopyable types. By marking a struct or enum with the @_moveOnly attribute (or ~Copyable syntax in future versions), you declare it cannot be copied. This allows only one instance to exist at a time, shared across your code.

Benefits of Noncopyability:

  • Efficiency: Say goodbye to unnecessary copying, saving memory and boosting performance — especially for larger data structures.
  • Resource management: Ideal for representing unique resources like file handles or network connections, ensuring exclusive access.
  • Thread safety: Simplifies reasoning about shared state, reducing opportunities for data races in multithreaded applications.
  • Deinitialization: Noncopyable types can have destructors (similar to classes), allowing for proper resource cleanup upon their demise.

Considerations and Use Cases:

  • Sharing vs. Ownership: Remember that only one instance exists. Passing around a noncopyable type means passing ownership, not a copy. Be mindful of how you manage this unique ownership in your code.
  • Not a Replacement for Classes: While offering some class-like behavior, noncopyable types lack features like inheritance and reference counting. Use them strategically where their benefits outweigh limitations.
  • Current Limitations: Generics and optionals cannot be noncopyable yet, but future versions might expand support.

Examples:

  • Representing a unique file handle, ensuring exclusive access and proper closing.
  • Modeling a single, shared global configuration object.
  • Creating thread-safe singletons without the complexity of full-fledged classes.

In Conclusion:

Noncopyable structs and enums are a powerful addition to Swift, unlocking new possibilities for efficient resource management, thread safety, and unique ownership scenarios. However, use them judiciously, considering their trade-offs and limitations. By understanding their potential, you can write cleaner, more performant, and resource-conscious Swift code!

Ready to explore? Check out the official documentation for deeper dive and start experimenting with noncopyable types in your projects!

--

--

Saeid Rezaeisadrabadi
Saeid Rezaeisadrabadi

Written by Saeid Rezaeisadrabadi

Over 8 years of experience in iOS software development

No responses yet