DataRepresentation
A transfer representation for types that provide their own binary data conversion.
Declaration
struct DataRepresentation<Item> where Item : TransferableMentioned in
Overview
Use this transfer representation if your model is stored in memory. For example, a drawing app might have a notion of a layer that can be converted to and from a custom binary data format and also converted to the PNG image type:
struct ImageDocumentLayer {
init(data: Data) throws { }
func data() -> Data { Data() }
func pngData() -> Data { Data() }
}You can provide multiple transfer representations for a model type, even if the transfer representation types are the same. The following shows the ImageDocumentLayer structure conforming to Transferable with two DataRepresentation instances composed together:
extension ImageDocumentLayer: Transferable {
static var transferRepresentation: some TransferRepresentation {
DataRepresentation(contentType: .layer) { layer in
layer.data()
} importing: { data in
try ImageDocumentLayer(data: data)
}
DataRepresentation(exportedContentType: .png) { layer in
layer.pngData()
}
}
}The example drawing app’s custom transfer representation comes first so that apps that know about the custom transfer representation can use it. The second transfer representation offers export compatibility with other apps that work with PNG images.
Avoid registering data with the UTType.data content type. Instead, choose a content type that best describes the data structure. For example, register PDF data with UTType.pdf so the data can be dragged, shared, or imported to apps that support that data type:
struct PDFDocument: Transferable {
var pdfData: Data
static var transferRepresentation: some TransferRepresentation {
DataRepresentation(contentType: .pdf) { pdfDocument in
pdfDocument.pdfData
} importing: { data in
PDFDocument(pdfData: data)
}
}