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
OutboundBodyThe type of the body element that the writer will produce.
Instance Properties
boundaryBoundary string used to separate parts in the multipart data.
Instance Methods
finish()Writes the final boundary to the multipart data.write(bytes:)Writes the given bytes to the multipart data.writeBodyChunk(_:)Writes a single body chunk.writeBodyChunks(_:)Writes multiple body chunks followed by a CRLF sequence.writeBoundary(end:)Writes a multipart boundary with optional termination.writeHeaders(_:)Writes HTTP header fields for a multipart part.writePart(_:)Writes a complete multipart part including boundary, headers, and body.
Relationships
Inherits From
Swift.SendableSwift.SendableMetatype