Skip to content

Protocol

MultipartWriter

A protocol that defines the interface for writing multipart data.
protocol MultipartWriter<OutboundBody> : Sendable

Overview

Writers conforming to this protocol can serialize multipart data by writing boundaries, headers, and body chunks in the proper multipart format. The protocol supports both streaming and buffered writing approaches.

Implementing a Custom Writer

Here’s an example of implementing a custom writer that accumulates data in memory:

struct MemoryMultipartWriter: MultipartWriter {
    typealias OutboundBody = [UInt8]

    let boundary: String
    private var buffer: [UInt8] = []

    init(boundary: String) {
        self.boundary = boundary
    }

    mutating func write(bytes: some Collection<UInt8> & Sendable) async throws {
        buffer.append(contentsOf: bytes)
    }

    mutating func finish() async throws {
        try await writeBoundary(end: true)
    }

    var data: [UInt8] {
        buffer
    }
}

// Usage example:
var writer = MemoryMultipartWriter(boundary: "boundary123")
try await writer.writeBoundary()
try await writer.writeHeaders([.contentType: "text/plain"])
try await writer.writeBodyChunk("Hello, world!".utf8)
try await writer.finish()
let result = writer.data

Topics

Associated Types

  • OutboundBody
    The type of the body element that the writer will produce.

Instance Properties

  • boundary
    Boundary string used to separate parts in the multipart data.

Instance Methods

Relationships

Inherits From

  • Swift.Sendable
  • Swift.SendableMetatype

Conforming Types