---
name: integrate-swift-client
description: >
  Use the generated Swift client in an iOS or macOS application. Covers
  adding the .swift file to Xcode, instantiation with URL and URLSession,
  async/await operation calls, Codable struct schemas, ApiResponse<T>,
  APIError enum handling, and Sendable conformance. Load when importing
  or using a generated swift-mode client file.
type: framework
library: openapi-client-generator
library_version: "3.0.0"
requires:
  - generate-client
sources:
  - "bazo/openapi-client-generator:src/modes/swift/index.ts"
  - "bazo/openapi-client-generator:src/modes/swift/query.ts"
  - "bazo/openapi-client-generator:src/modes/swift/mutation.ts"
---

This skill builds on generate-client. Read it first for CLI usage.

# Integrate Swift Client

## Setup

No external dependencies required. The generated file uses only Foundation.

Add the generated `.swift` file to your Xcode project, then instantiate:

```swift
let api = ApiClient(baseURL: URL(string: "https://api.example.com")!)
```

The constructor signature is:

```swift
init(baseURL: URL, session: URLSession = .shared)
```

### Keep the client out of your module's scope (`--namespace`)

Every generated type is declared at module scope by default. Compiled into an app target, a spec's
`Label`, `Duration`, `User` or `Tag` then shadows SwiftUI's and the standard library's in **every**
file of that target (`Label("Open", systemImage:)` stops compiling). Pass `--namespace` to wrap the
runtime helpers, schemas and client class in one enum:

```bash
openapi-client-generator forgejo.json Generated -n Client -m swift --namespace Forgejo
```

```swift
let api = Forgejo.Client(baseURL: URL(string: "https://git.example.com/api/v1")!)
let run: Forgejo.ActionRun = try await api.actionRun(owner: "o", repo: "r", runId: 1).data
catch let error as Forgejo.APIError { … }
```

Inside the namespace nothing changes; outside it, only the namespace name is declared.

## Core Patterns

### Call a query operation

```swift
let result = try await api.listTasks(page: 1, limit: 10)
print(result.data.items) // [Task]
print(result.status) // 200
```

All operations are `async throws` functions. Query parameters map to function parameters with defaults for optional ones.

### Call a mutation operation

```swift
let newTask = CreateTaskRequest(title: "Build feature", status: "todo", description: nil)
let result = try await api.createTask(body: newTask)
print(result.data.id) // created task ID
```

Mutations take a `body` parameter typed as the corresponding Codable request struct.

### Handle API errors

```swift
do {
    let result = try await api.getTask(taskId: "nonexistent")
} catch let error as APIError {
    switch error {
    case .documentedResponse(let statusCode, let payload, _, _):
        // A non-2xx status the spec declares, with its error body decoded.
        print("HTTP \(statusCode): \(payload)")
    case .undocumentedResponse(let statusCode, let data, _, _):
        // A status the spec does not declare, or a declared one whose body is not the
        // documented error shape. The raw bytes come with it.
        print("HTTP \(statusCode), \(data.count) undocumented bytes")
    case .decodingError(let underlying):
        // A documented 2xx whose body does NOT match its schema. `underlying` is the
        // DecodingError, so it names the field that failed.
        print("Decode failed: \(underlying)")
    default:
        print("Request failed: \(error)")
    }
}
```

A documented non-2xx status throws `APIError.documentedResponse` carrying its decoded error
payload; an undeclared status, or a declared one whose body does not match, throws
`APIError.undocumentedResponse` with the raw bytes. A documented **2xx** whose body does not match
its schema throws `APIError.decodingError`, wrapping the `DecodingError` itself — so the reason
survives to the caller, the way the kotlinx `SerializationException` does in the Kotlin client.
Kotlin is the mode this brings Swift into step with; the full and playwright clients are lenient
about a malformed documented 2xx whose schema is a union (they accept whichever branch validates)
and the PHP client types a union `mixed`, so neither has a decoding reason to report for that
shape. **This is a change**: the client used
to swallow that reason and report the same `undocumentedResponse` an undeclared status produces,
which left a caller with the bytes but no idea which field was wrong. Code that matched
`undocumentedResponse` to catch a malformed success body must now match `decodingError`.

### Use a custom URLSession

```swift
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = ["Authorization": "Bearer \(token)"]
let session = URLSession(configuration: config)
let api = ApiClient(baseURL: URL(string: "https://api.example.com")!, session: session)
```

### Replace the transport (tests, custom networking)

`transport` performs the HTTP exchange in place of `session.data(for:)` when set. It receives the
request after `requestModifier`, so auth headers are already on it:

```swift
api.transport = { request in
    let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
    return (Data(#"{"id":"42"}"#.utf8), response)
}
```

Set it (and `requestModifier`) once, right after constructing the client — both are plain stored
properties on an `@unchecked Sendable` class.

### Wire names that are not Swift identifiers

A spec is free to name a field `a.b`, `2fa`, `first name` or `@type`. None of those can be a Swift
property name, so the generator folds each into a legal one — camel-casing across the characters
Swift cannot spell, prefixing a leading digit — and the struct's `CodingKeys` carries the original
key, so nothing changes on the wire:

```swift
struct Thing: Codable, Sendable {
    let aB: String
    let _2fa: String
    let firstName: String

    enum CodingKeys: String, CodingKey {
        case aB = "a.b"
        case _2fa = "2fa"
        case firstName = "first name"
    }
}
```

A field whose name is a Swift keyword keeps that name, backtick-escaped in both positions — the
declaration and the `CodingKeys` case — and still decodes from the unescaped key:

```swift
    let `class`: String

    enum CodingKeys: String, CodingKey {
        case `class`   // decodes from "class"
    }
```

Enum raw values and every wire name are emitted through one escaper, so a `"`, a `\` or a control
character in the spec comes out as a valid Swift literal (`case ab = "a\"b"`). Do not "tidy" those
backslashes away — they are what keeps the value correct. A lone surrogate is the one thing Swift
cannot express and is not preserved.

Query, header and multipart names are emitted as literal strings, so they are never folded. Two
field names that would fold onto the SAME property (`a.b` and `a-b`) are a generation error, not a
silent rename — rename one of them in the spec.

Enum VALUES fold the same way (`Male`, `male` and `MALE` all give `male`), but they are NOT an
error: two enum values are not an ambiguity in the spec, so the duplicates are suffixed —
`case male = "Male"`, `case male_ = "male"`, `case mALE = "MALE"` — and every case keeps its own
raw value, so all three still round-trip. A reserved-word case takes the suffix inside its escape
(`` `default_` ``). Suffixing is order-dependent, so it is stable for a given spec but a value
inserted ahead of a colliding one shifts the names after it; refer to a case through the generated
identifier, never by assuming a spelling.

### A schema with both `properties` and a `oneOf`

`{ type: object, properties: { album }, oneOf: [Song, Podcast] }` means "an object with `album`
that additionally satisfies one of the branches". The generator distributes the top-level
properties over every branch, so each case payload is a struct carrying them alongside that
branch's own fields:

```swift
struct SleeveOneOf1: Codable, Sendable { let album: String; let track: String }
struct SleeveOneOf2: Codable, Sendable { let album: String; let episode: String }
enum Sleeve: Codable, Sendable { case option1(SleeveOneOf1); case option2(SleeveOneOf2) }
```

Pick a case and fill in both halves; there is no separate slot for the shared properties. All five
modes distribute identically, so the parts on the wire are the same from each. (A `type: "null"`
branch of a nullable `anyOf` is left alone, and a schema that also carries `allOf` or `enum` is
not distributed — a schema carrying both already reads inconsistently (the type-annotation
resolvers test `allOf` before the union, the Swift and Kotlin declaration generators test the union
first), and distributing would only change which of those two pre-existing readings wins, in some
modes and not others. A sibling `allOf` is
instead MERGED: the top-level properties become one more `allOf` member, so they reach the
generated type rather than being dropped.)

When the spec declares a `discriminator`, the generated `init(from:)` reads it first: it peeks at
the tag property in a keyed container and switches straight to the branch the mapping names (a
branch missing from the mapping answers to its own schema name, per OpenAPI). Only if the tag is
absent, unreadable, or matches nothing does it fall through to trying each branch in declaration
order and taking the first that decodes. This is the same two-step the Kotlin serializer's
`when (tag)` performs, so both clients return the same branch for the same bytes — including for
branches that overlap structurally, where trial decoding alone answered with whichever one was
declared first and silently dropped the fields only the other declares. The implicit-name rule (no
`mapping`: the tag is the branch's own schema name) now holds in the full and playwright clients
too, so all four typed modes pick the same branch for a mapping-less discriminator. An ANONYMOUS
branch — one the spec spells inline, with no schema name — has no name to answer to, so it is never
selected by tag and stays reachable only through trial decoding.

A tag the mapping DOES name is decoded strictly: if that branch fails to decode, the failure is
NOT swallowed into a fallback onto a branch the spec has ruled out. Through the generated client
that surfaces as `APIError.decodingError(underlying)`, whose `underlying` `DecodingError` names the
field that was missing — call `getEvent(eventId:)` on `{"kind":"system","id":"x"}` where
`SystemEvent` also requires `severity` and you catch that, not a decoded `UserEvent`. Kotlin
behaves the same (its caller gets a `JsonConvertException` naming the field); the full and
playwright clients are lenient here and return whichever bare option validates.

**This is a behaviour change at the client surface.** Before the discriminator was read, that same
call returned HTTP 200 with a `UserEvent` — the wrong branch, silently, with `severity`'s absence
never mentioned. It now throws. A caller that treated every 200 as decodable needs a `catch`.

Without a `discriminator` the decoder is pure trial decoding, and the first branch that decodes
wins. OpenAPI 3.1's `kind: { type: string, const: "system" }` disambiguates that case without a
discriminator: a STRING `const` is read as a one-value enum, the branch's `kind` becomes a one-case
Swift `enum`, the wrong branch stops decoding, and trial decoding lands on the right one. (A
boolean, integer or `null` `const` stays a plain `Bool`/`Int`/`AnyCodable` — narrowing those to a
`String`-raw enum could not decode the real bytes.)

Two consequences worth knowing. The branch types are **generated** (`<Union>OneOf1`, `<Union>OneOf2`),
so the original branch schemas stay declared but are no longer referenced by the union — and if a
spec of yours already used this shape, the case names change (`case .namedUpload(NamedUpload)` →
`case .option1(SleeveOneOf1)`). And because distribution reaches **response** schemas too, the
shared properties are now required in every branch: a response that omits one fails to decode where
it previously did not. That is what the spec asks for, but it is stricter than before.

## File uploads (multipart)

An operation whose request body is `multipart/form-data` takes a generated request struct where each `format: binary` field is typed `FilePart`:

```swift
let body = UploadTaskAttachmentMultipartFormDataRequest(
    file: FilePart(data: try Data(contentsOf: fileURL), filename: "invoice.pdf", mimeType: "application/pdf"),
    description: "Q3 invoice"
)
let result = try await api.uploadTaskAttachment(taskId: "42", body: body)
```

`FilePart` is `init(data: Data, filename: String, mimeType: String? = nil)`. The client encodes the multipart body itself (boundary generation, `Content-Disposition` headers) — you only construct the struct.

Field encoding rules: scalar fields become one part; arrays of scalars become repeated parts under the same field name; objects and array-of-object fields become a single part carrying their JSON as a plain text field — no filename and no `Content-Type: application/json`, so a strict multipart parser reads it as a field whose value is the JSON text, exactly as the full and playwright clients send it; `Optional` fields that are `nil` are omitted entirely. A multipart body that is itself optional (e.g. `body: SomeRequest? = nil`) still encodes a well-formed (empty) multipart envelope when omitted, not a bodyless request. A `oneOf`/`anyOf` body is a generated `enum` with one case per branch; the client switches on the case and sends that branch's own fields, which are the same parts the other four modes send for the same branch. A union body's branches must each have a field set of their own: if any branch has none — a primitive, an array, or an object with no declared properties — the whole body falls back to sending no parts at all, in every mode alike. The same fallback applies to a union the Kotlin generator cannot express as a sealed class (most reachably when a schema named `<UnionName>Serializer` already exists, but also when the union carries a sibling `enum` or is an `anyOf` of one type plus `null`), because Kotlin then has no sum type to dispatch on and the five modes only stay in step by all sending nothing. A `oneOf`/`anyOf` **urlencoded** body dispatches on the branch in exactly the same way, sending that branch's own fields as `k=v` pairs — an array field as repeated keys, an object-valued field as one JSON-encoded value — and it takes the same fallback, with the same explanatory comment, only when the branches cannot be described. A SINGLE-variant `anyOf` (`anyOf: [$ref Only]`) is not a union at all: it is simply its branch, typed and sent as that object in every mode. A schema carrying BOTH top-level `properties` and an `allOf` means "an object with those properties that ALSO satisfies every member of the allOf": the generator folds the properties in as one more `allOf` member, so they appear in the generated type and on the wire alongside the composed base's fields (they used to be dropped from the type while the form walk still emitted a part for them). The folded properties go LAST, so they WIN any name they share with the base: a sibling `count: { type: string }` over a base's `count: { type: integer }` types the field `string`. That has always been this mode's reading; the full and playwright clients now agree, where before they emitted an intersection no payload could satisfy. A `nullable` field is treated exactly like an omitted one: a `nullable` scalar sends no part when it is `nil` even if the spec marks it required, and a `nullable`-item array (`[String?]`, `[FilePart?]`) skips its `nil` elements rather than sending an empty or `"null"` part for them.

Form-urlencoded bodies (`application/x-www-form-urlencoded`) take a generated request struct; the client percent-encodes and joins its fields into the request body for you. Scalar and enum fields become one pair, arrays become repeated pairs sharing the name, and an object field is JSON-encoded into a single pair value. A `format: binary` field in a urlencoded body is not a file part and not `Data` — a urlencoded body cannot carry a file, so it is typed `String` and sent verbatim, the same as in the other four modes:

```swift
let body = RequestTokenApplicationXWwwFormUrlencodedRequest(
    grantType: .password,
    clientId: "abc",
    clientSecret: nil,
    scopes: ["read", "write"]
)
let result = try await api.requestToken(body: body)
```

Array-valued fields are sent as repeated keys, not indexed ones — `scopes: ["read", "write"]` encodes as `scopes=read&scopes=write`.

Two byte-level differences from the other four modes on this path, both pre-existing and both harmless to a conforming server, but worth knowing if you diff raw request bodies across modes:

- **A space encodes as `%20`, not `+`.** `formURLEncodedBody` percent-encodes everything outside `[A-Za-z0-9-._~]`, so `note: "a b"` goes out as `note=a%20b` where full, playwright, Kotlin and PHP all send `note=a+b`. Both spellings decode to the same string under `application/x-www-form-urlencoded`.
- **Key order inside a JSON-encoded value is not guaranteed.** An object-valued field is encoded with a plain `JSONEncoder`, which has no `.sortedKeys`. A generated struct still encodes in its declared property order, but a free-form map (`[String: AnyCodable]`) follows Swift's per-process dictionary ordering, so the JSON text in that one pair can differ run to run — and from the other four modes, which preserve insertion order.

Raw binary bodies (`application/octet-stream`, `image/*`, …) take a `FilePart` directly as the body, sending `.data` as the raw request body:

```swift
let result = try await api.uploadRawBlob(body: FilePart(data: try Data(contentsOf: fileURL), filename: "blob.bin", mimeType: "application/octet-stream"))
```

A `text/*` body whose schema is a `string` (Forgejo's `renderMarkdownRaw` takes `text/plain`) is a
plain `String` parameter, sent as its UTF-8 bytes under the declared media type — never JSON-encoded,
which would wrap it in quotes. Every request's `Accept` header lists the media types the operation's
2xx responses document (`text/plain` for a log download), falling back to `application/json`.

## Recursive schemas

A struct cannot store its own type inline, so a property that leads back to its own struct —
directly (`Repository.parent: Repository`) or through other structs (`A.b → B.a → A`) — is stored
in a box:

```swift
let parent: Indirect<Repository>?

let name = repo.parent?.value.fullName
let child = Repository(/* … */, parent: Indirect(parentRepo), /* … */)
```

`Indirect<T>` is a `final class` (`Codable`, `Sendable`) and is transparent on the wire: it encodes
and decodes exactly as `T`. Only properties inside a cycle are boxed; arrays (`[Node]`) never are,
and a `oneOf`/`anyOf` enum in a cycle is declared `indirect enum` instead.

## Names the generator changes

- **Operation methods are lowerCamelCase.** `ActionRun` → `func actionRun(…)`, `ListActionRuns` →
  `listActionRuns`, a leading acronym lowers as a unit (`HTMLPage` → `htmlPage`). Declared verbatim,
  `func ActionRun` shadowed the `ActionRun` struct inside the client class. **This is a change** for
  specs with PascalCase operationIds; two operationIds that fold to the same name are a generation
  error.
- **A schema named like a runtime or Foundation type is suffixed** — `APIError` → `APIError2` — the
  helper types (`APIError`, `ApiResponse`, `AnyCodable`, `Empty`, `FilePart`, `Indirect`), the client
  class itself, and the Foundation/standard types the client code names (`URL`, `Data`, `String`, …).

## Common Mistakes

### HIGH Providing String instead of URL for baseURL

Wrong:

```swift
let api = ApiClient(baseURL: "https://api.example.com")
```

Correct:

```swift
let api = ApiClient(baseURL: URL(string: "https://api.example.com")!)
```

The constructor parameter is typed as `URL`, not `String`. Use `URL(string:)` which returns an optional — force-unwrap only for known-good URLs.

Source: src/modes/swift/index.ts generateClient

### HIGH Not using async/await for operations

Wrong:

```swift
let result = api.getTask(taskId: "123")
```

Correct:

```swift
let result = try await api.getTask(taskId: "123")
```

All generated operations are `async throws` functions. They must be called with `try await` from an async context.

Source: src/modes/swift/query.ts

### HIGH Editing the generated file directly

Wrong:

```swift
// Adding a custom method directly in ApiClient.swift
class ApiClient: @unchecked Sendable {
    // ...generated code...
    func customMethod() async throws { /* hand-written */ }
}
```

Correct:

```swift
// Extend in a separate file
extension ApiClient {
    func customMethod() async throws { /* hand-written */ }
}
```

The generated output is meant to be regenerated from the spec. Manual edits are overwritten on the next generation run. Use Swift extensions in a separate file for custom methods.

Source: maintainer interview

See also: generate-client/SKILL.md — CLI usage for regenerating the client
