Hamp 2025. 12. 14. 16:11
반응형

🎥 Transferable

 

✅ 정의

 

기존에는 데이터 전달 방식이 제각각, 코드가 복작합고 타입이 안전하지 않음

 

  • Drag & Drop → NSItemProvider
  • Photos → loadTransferable
  • Share → 각자 다른 API

 

 

 

 

🧩 역할

 

  • 타입 안전환 데이터 변환
  • 여러 전송 메커니즘을 하나의 추상화로 통합
이 프로토콜을 채택하는 타입은 어떤 형식(UTType)으로 어떻게
encode /decode 될 수 있는 지 시스템에게 알려주는 역할

 

 

🧱 구조

public protocol Transferable {

    /// import / export할 item 정보를 다음 객체
    associatedtype Representation : TransferRepresentation

	/// @resultBuilder 형식으로, 여러개를 쉽게 정의
    @TransferRepresentationBuilder<Self> static var transferRepresentation: Self.Representation { get }
}
public protocol TransferRepresentation<Item> : Sendable {

    /// import/export 될 타입
    associatedtype Item : Transferable

    /// representation 객체
    associatedtype Body : TransferRepresentation

	// @resultBuilder를 이용하여, 
    @TransferRepresentationBuilder<Self.Item> var body: Self.Body { get }
}

 

 

🚀 특징

 

대표적인 TransferRepresentation 객체들을 다음과 같다.

 

DataRepresentation

  • 메모리 기반 (Data)
  • Copy / Paste, Share에 주로 사용
  • 작은 데이터에 적합

FileRepresentation

  • 파일 기반(URL)
  • 이미지, 동영상, PDF 등
  • PhotoPicker, Drag & Drop 등

CodableRepresentation

  • Codable 타입을 자동으로 Data로 치환
  • JSON, plist 등

 

🧪 예시

struct Movie: Transferable {
  let url: URL

  static var transferRepresentation: some TransferRepresentation {
    FileRepresentation(
      contentType: .movie,
      exporting: { movie in
        SentTransferredFile(movie.url) // 밖으로 나갈 때
      },
      importing: { received in
        let copy = URL.documentsDirectory.appending(path: "movie.mp4")

		// 덮어쓰기
        if FileManager.default.fileExists(atPath: copy.path()) {
          try FileManager.default.removeItem(at: copy)
        }

		// Movie 인스턴스로 리턴
        try FileManager.default.copyItem(at: received.file, to: copy)
        return Self.init(url: copy)
      }
    )
  }
}

출처

https://developer.apple.com/documentation/coretransferable/transferable

 

Transferable | Apple Developer Documentation

A protocol that describes how a type interacts with transport APIs such as drag and drop or copy and paste.

developer.apple.com

 

반응형