skip to content

In Core Transferable, how do you choose among CodableRepresentation, DataRepresentation, FileRepresentation and ProxyRepresentation, and why does their order matter?

level: middleimportance: should knowfreq 45%

answer

  1. in memory, on disk, or borrowed
  2. Codable models skip the byte code
  3. large payloads travel as files
  4. the earliest entry is preferred
  5. labels set import, export or both

basics

~20 s

Use CodableRepresentation for a Codable model, DataRepresentation for in-memory bytes, FileRepresentation for large content on disk and ProxyRepresentation to reuse another Transferable type. List the most faithful first: earlier entries are preferred, later ones are compatible fallbacks.

solid answer

~40 s

Core Transferable ships four building blocks. `CodableRepresentation` encodes a `Codable` model, as JSON by default, under a content type you name. `DataRepresentation` converts an in-memory value to and from `Data` in a format such as PNG or vCard. `FileRepresentation` moves content as a file URL, which suits large data because the receiver loads it only if needed. `ProxyRepresentation` lets another `Transferable` type, such as `String`, stand in for yours. Inside `transferRepresentation` the order is a preference list: put the representation that most accurately describes the type first, then less faithful but more compatible ones, so an app that knows your custom type gets the full model and a text editor gets text. Initializer labels set direction: `contentType:` imports and exports, `exportedContentType:` only exports, `importedContentType:` only imports.

code

swift · 27 lines
swift
import SwiftUI
import UniformTypeIdentifiers

extension UTType {
    static let moodCard = UTType(exportedAs: "com.example.moodboard.card")
}

struct MoodCard: Codable, Transferable {
    var caption: String
    var thumbnailPNG: Data

    static var transferRepresentation: some TransferRepresentation {
        // 1. Most faithful: the whole card, for this app and its siblings.
        CodableRepresentation(contentType: .moodCard)
        // 2. Export-only image for photo and drawing apps.
        DataRepresentation(exportedContentType: .png) { card in
            card.thumbnailPNG
        }
        .suggestedFileName { $0.caption + ".png" }
        // 3. Least faithful, most compatible: plain text, both ways.
        ProxyRepresentation { card in
            card.caption
        } importing: { text in
            MoodCard(caption: text, thumbnailPNG: Data())
        }
    }
}

go deeper

for a junior

Recall the four representation types and which fits a Codable model, in-memory bytes, a file on disk, or a stand-in type such as String.

for a middle

Explain that the builder's order is a preference list and how the contentType, exportedContentType and importedContentType labels set direction.

for a senior

Justify a production list: custom type first, standard formats next, a String proxy last, files for large media, and visibility or exporting conditions where content must not leak.

for a principal

Decide which external formats the product promises to read and write, since each exported representation is a long-lived interface other apps will depend on.

## Four building blocks A `Transferable` type's `transferRepresentation` is a list of **transfer representations**. Core Transferable defines four that you compose: | Representation | Use it when | What crosses the boundary | |---|---|---| | `CodableRepresentation` | The model is already `Codable` | Encoded bytes, JSON by default, under your content type | | `DataRepresentation` | The whole value lives in memory and has a binary format | `Data` you produce and parse | | `FileRepresentation` | The content is large or already on disk | A file URL; the receiver loads it only if it needs to | | `ProxyRepresentation` | Another `Transferable` type can stand in | That type's own representation, such as plain text | `CodableRepresentation(contentType:)` uses `JSONEncoder` and `JSONDecoder`; the `init(for:contentType:encoder:decoder:)` overload accepts other top-level coders whose output is `Data`. Because it usually means you are defining a new data type, Apple's documentation reminds you to declare that type in the app's Info.plist. `ProxyRepresentation` is a convenience, and Apple says its evaluation isn't supposed to be calculation-heavy: no network requests, file operations or other time-consuming work in its closures. Use `FileRepresentation` or `DataRepresentation`, whose closures are `async`, for lengthy tasks. ## Order is a preference list The builder reads top to bottom, and the order **expresses preference**: 1. Put the representation that most accurately represents the type first, usually a `CodableRepresentation` or `DataRepresentation` under your custom type. 2. Follow it with widely understood formats, such as an exported PNG or a vCard. 3. End with the most compatible and least faithful fallback, typically a `ProxyRepresentation` to `String`. Apple's documentation describes the effect with a to-do item: if the receiver knows the custom content type, it receives that type; a text editor that doesn't gets the plain-text proxy instead. Putting the proxy first would make plain text the preferred format, so receivers able to read the full model might get only text. The same rule explains the in-app case. Apple's drawing-layer example says that when a layer is dropped within the app, or onto another app that recognizes the custom layer type, the first representation is used; a different image editor, which likely recognizes PNG, gets the second. Your own app is simply the receiver that understands the most. ## Direction: import, export or both Each representation can support importing (a drop, a paste, a received share), exporting (a drag out, a copy, a share), or both. The initializer labels decide: - `DataRepresentation(contentType:exporting:importing:)` and `FileRepresentation(contentType:shouldAttemptToOpenInPlace:exporting:importing:)` work both ways. - Initializers labelled `exportedContentType:` only export, such as a PNG thumbnail you produce but never parse. - Initializers labelled `importedContentType:` only import. - `ProxyRepresentation(exporting:)` only exports, `ProxyRepresentation(importing:)` only imports, and `ProxyRepresentation(exporting:importing:)` does both. A type may list the same representation type more than once; Apple's drawing-layer example uses two `DataRepresentation`s, one for a custom layer format and one exporting PNG. ## Modifiers that refine a representation - **`suggestedFileName(_:)`** names the file if the receiver writes the item to disk. The string form is iOS 16; the closure form, which receives the item, is iOS 17. If several are given, only the last is used. - **`visibility(_:)`** limits who sees a representation in transit: `.all` (any app or process), `.team` (apps from your development team), `.ownProcess` (only the source app). `.group` targets macOS apps in the same App Group and is unavailable on iOS. - **`exportingCondition(_:)`** stops a representation from exporting values that don't meet a condition, such as a CSV export only when the content supports it. ## Content types Choose the most specific `UTType` that describes the payload. Apple advises against registering in-memory data as the generic `UTType.data`, and for files recommends a type such as `UTType.pdf` over `UTType.fileURL` or `UTType.content`, so the data can be dragged, shared or imported into apps that support that type. Declare your own exported type for your own format. The coder behind `CodableRepresentation` is a separate choice from the content type. The default initializer uses JSON; passing `encoder: PropertyListEncoder(), decoder: PropertyListDecoder()` to `init(for:contentType:encoder:decoder:)` switches the bytes to a property list, and the content type you declare should then describe that format. ## Spelling With the iOS 27 SDK, a key-path proxy needs its label: `ProxyRepresentation(exporting: \.caption)` compiles, while the unlabeled form that some of Apple's sample code uses, here `ProxyRepresentation(\.caption)`, fails with "missing argument label 'exporting:'".

  • When would you pick FileRepresentation over DataRepresentation for an image?
    When the image is large or already stored as a file. `FileRepresentation` passes a file URL, which Apple calls efficient because the receiver loads the content into memory only if needed, while `DataRepresentation` hands over the whole `Data` value. A small thumbnail generated in memory fits `DataRepresentation`; a full-resolution photo on disk fits `FileRepresentation`.
  • How do you keep the full-fidelity representation inside your own app?
    Apply `.visibility(.ownProcess)` to it, so only the app that started the transfer sees that representation, while later entries such as a `String` proxy stay visible to other apps. `.team` widens it to apps from the same development team; `.group` is macOS-only.

  • The order of representations is irrelevant; the system always picks the richest one.
  • ProxyRepresentation closures are a good place to fetch data from the network.
  • CodableRepresentation encodes a property list unless told otherwise.
  • Registering everything as UTType.data makes the type acceptable to every app.
  • Every representation has to support both import and export.