The Transferable protocol is Apple’s modern, Swift-native way to allow data to be shared across your app or between different apps. It standardizes how objects are serialized (converted to exportable data) and deserialized (imported back into objects) during operations like drag and drop, copy/paste, and system sharing sheets.
Here is a breakdown of how it works and its core concepts:
1. Basic Requirements
To make a custom type conform to Transferable, you implement a single static property called transferRepresentation. This property defines the rules for how your data is converted depending on how it is stored or shared.
2. Types of Transfer Representations
Depending on your model's underlying structure, Core Transferable provides built-in representation wrappers:
CodableRepresentation: Best for custom data models that already conform to Swift’s Codable protocol. It handles JSON/property-list encoding and decoding automatically.
DataRepresentation: Best for raw data blobs held in memory (e.g., custom byte buffers or image data).
FileRepresentation: Best for large files or assets on disk (e.g., videos, PDFs) so they can be streamed directly from a file path rather than loaded entirely into RAM.
You can also use a TransferRepresentationBuilder to chain multiple representations together, declaring fallback formats in order of preference.
3. Proxy Representations
If your model object doesn't need its own direct serialization format, you can use a ProxyRepresentation. This converts your custom object into another type that is already transferable (e.g., exporting a complex Document model as a plain String or URL).
4. SwiftUI Integration
SwiftUI natively supports Transferable types, simplifying UI interaction features:
Drag and Drop: Views can easily act as drag sources using modifiers like draggable(_:) or drop destinations using dropDestination(for:action:).
Built-in Support: Common Swift and Apple framework types like String, URL, Data, and Image already conform to Transferable out of the box, making standard sharing seamless.