skip to content

In SwiftUI, how do you make a custom model type draggable into other apps and droppable back, using the Transferable protocol?

level: middleimportance: must knowfreq 62%

answer

  1. one conformance for every transfer API
  2. a static builder property
  3. reverse-DNS type, in code and Info.plist
  4. a source modifier and a destination modifier
  5. a text fallback in both directions

basics

~20 s

Conform the model to Transferable with a static transferRepresentation, such as a CodableRepresentation under a custom exported UTType plus a ProxyRepresentation to String. Then add draggable(card) to the source view and dropDestination(for: MoodCard.self) to the target.

solid answer

~40 s

`Transferable` (Core Transferable, iOS 16) has one requirement: a static `transferRepresentation`, listed in order of preference. For a `Codable` card, `CodableRepresentation(contentType: .moodCard)` sends JSON under a custom type declared in code with `UTType(exportedAs: "com.example.moodboard.card")` and in Info.plist under `UTExportedTypeDeclarations`. Other apps don't know that type, so add a `ProxyRepresentation` to `String` with both an exporting and an importing closure: a text editor receives the caption, and text dropped from it becomes a card. On the view side, `.draggable(card)` makes a view a drag source and `.dropDestination(for: MoodCard.self)` hands the target a `[MoodCard]`. The same conformance drives `ShareLink` and `PasteButton`, so nothing in the model is drag-specific.

code

swift · 32 lines
swift
import SwiftUI
import UniformTypeIdentifiers

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

struct MoodCard: Codable, Identifiable, Transferable {
    var id = UUID()
    var caption: String

    static var transferRepresentation: some TransferRepresentation {
        CodableRepresentation(contentType: .moodCard)
        ProxyRepresentation { $0.caption } importing: { MoodCard(caption: $0) }
    }
}

struct BoardView: View {
    @State private var cards: [MoodCard] = []
    @State private var isTargeted = false

    var body: some View {
        List(cards) { card in
            Text(card.caption).draggable(card)
        }
        .background(isTargeted ? Color.accentColor.opacity(0.15) : .clear)
        .dropDestination(for: MoodCard.self) { dropped, _ in
            cards.append(contentsOf: dropped)
            return !dropped.isEmpty
        } isTargeted: { isTargeted = $0 }
    }
}

go deeper

for a junior

Recall the pair of modifiers, draggable on the source and dropDestination on the target, and that both work with a Transferable type.

for a middle

Walk through the conformance: the static transferRepresentation, a custom exported UTType declared in code and Info.plist, and a String proxy as the compatible fallback.

for a senior

Show the production details: an importing closure on the fallback, a custom drag preview, export work kept off the main actor, and checking which formats other apps receive.

for a principal

Treat the exported content type as a contract with other apps and with future versions of your own, and decide which formats the team commits to keep readable.

## One protocol behind every transfer **`Transferable`** comes from the Core Transferable framework (iOS 16) and describes how a type moves through transport APIs: drag and drop, the share sheet and the pasteboard. SwiftUI's transfer APIs all accept it: - **`draggable(_:)`** makes a view the source of a drag. - **`dropDestination(for:action:isTargeted:)`** makes a view accept drops of a given type. - **`ShareLink`** shares an item through the system share sheet. - **`PasteButton(payloadType:onPaste:)`** reads items of a type from the pasteboard; on iOS it validates itself as the pasteboard changes. Conform once and every one of them works with your model. `String`, `Data`, `URL` and SwiftUI's `Image` already conform, so they can be dragged or pasted with no extra code. ## The one requirement The protocol requires a single static property, `transferRepresentation`, written with the `@TransferRepresentationBuilder` result builder. Each line inside it is a **transfer representation**: a recipe for turning the value into some content type and, optionally, back again. `Transferable` also refines `Sendable`, so the model is expected to be safe to pass between concurrency domains; a struct of sendable properties is the simple case. ## Step by step for a mood-board card 1. **Name a content type.** Declare a reverse-DNS identifier in code: `static let moodCard = UTType(exportedAs: "com.example.moodboard.card")`. 2. **Declare it in Info.plist.** Apple's documentation tells you to include a matching entry for any custom type identifier you declare: the Exported Type Identifiers key, `UTExportedTypeDeclarations`, with the type conforming to `public.data` (or `com.apple.package`) so the system knows how to handle it. 3. **Conform the model.** Make the card `Codable` and list `CodableRepresentation(contentType: .moodCard)` first; it encodes the whole card with `JSONEncoder` unless you pass your own encoder and decoder. 4. **Add a fallback.** Most apps will never know your custom type, so add a `ProxyRepresentation` to `String`. Its exporting closure gives text editors the caption; its importing closure turns dropped text into a new card. 5. **Mark the source.** Apply `.draggable(card)` to the card's view. SwiftUI adds the drag-and-drop gestures and renders the view as the drag preview; `draggable(_:preview:)` takes a custom preview view instead. 6. **Mark the destination.** Apply `.dropDestination(for: MoodCard.self) { cards, location in ... }` to the board. The action receives the decoded `[MoodCard]` and the drop point and returns a `Bool` for whether you handled the drop; an `isTargeted` closure tells you when a drag hovers, so you can highlight the board. ## What each representation contributes | Representation | Receiver that uses it | Direction | |---|---|---| | `CodableRepresentation(contentType: .moodCard)` | This app and any app that knows the custom type | Import and export | | `ProxyRepresentation` to `String`, both closures | Notes or any text editor | Import and export | | `ProxyRepresentation(exporting: \.caption)` | Text receivers | Export only | Order matters: the first representation is the most faithful and preferred one, and later ones are more compatible fallbacks. A receiver that understands the custom type gets the full card; a plain text field gets the caption. Apple's layer example spells out the in-app case: when a value is dropped within the app, or onto an app that recognizes the custom type, the first representation is used. ## Receiving through paste The same conformance serves the pasteboard. `PasteButton(payloadType: MoodCard.self) { cards in ... }` declares the type it accepts, and when the person taps it the closure receives the pasteboard items converted to `[MoodCard]` through the card's import representations. The system supplies the button's appearance and label, which `buttonBorderShape(_:)`, `labelStyle(_:)` and `tint(_:)` adjust in some contexts. Apple notes that on iOS the button validates and invalidates itself as the pasteboard changes, which it does not do on macOS. Like `ShareLink`, it arrived in iOS 16, so it is part of the iOS 17 baseline. ## Pitfalls interviewers probe - **An export-only fallback.** `ProxyRepresentation(exporting: \.caption)` sends text out but cannot build a card from text, so text drops are ignored. Add an `importing:` closure when you want both directions. - **Spelling the proxy.** Some of Apple's sample code uses the unlabeled key-path form, such as `ProxyRepresentation(\.title)`, but with the iOS 27 SDK the compiler rejects that with "missing argument label 'exporting:'". - **Main-actor work during export.** Apple's `draggable(_:)` documentation says that doing work on the main actor while exporting the item isn't supported and might cause a hang, and that the exporting closure shouldn't dispatch to the main actor. - **Forgetting the plist entry.** The `UTType(exportedAs:)` line in code mirrors the declaration; the system learns about new content types from apps' Info.plist files. - **Reaching for a gesture.** A `DragGesture` moves a view by tracking a finger; it carries no data to another view or app. - **Mixing APIs.** `onDrag(_:)` and `onDrop(of:isTargeted:perform:)` are the older item-provider APIs built on `NSItemProvider`; Apple's documentation prefers `Transferable` items in Swift.

  • Why add a ProxyRepresentation when the card already has a CodableRepresentation?
    The custom `com.example.moodboard.card` type means nothing to Notes or a text field, so a drop there would find no format it accepts. A `ProxyRepresentation` to `String` reuses String's own conformance as a less faithful fallback, and listing it after the Codable entry keeps the full card for receivers that understand the custom type.
  • How do you change what the user sees while dragging a card?
    Use `draggable(_:preview:)` and return a view, such as a small thumbnail, from the preview closure; SwiftUI shows it instead of a rendering of the source view. To adjust only the lift preview's shape, apply `contentShape(.dragPreview, RoundedRectangle(cornerRadius: 12))` before `draggable`.
  • Why does Apple warn against main-actor work in a draggable item's export?
    The `draggable(_:)` documentation says doing work on the main actor while exporting the item isn't supported and might cause a hang, and that the exporting closure shouldn't dispatch to the main actor. Representation closures are `@Sendable`, so build the export from the value itself instead of reaching back into view state.

  • Making the model Codable is enough for draggable(_:) to accept it.
  • UTType(exportedAs:) in code registers the type, so Info.plist needs nothing.
  • A DragGesture is how you move a model's data into another app.
  • ProxyRepresentation(exporting:) also lets dropped text create a new card.
  • Drag and drop and ShareLink each need a separate conformance protocol.