> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Swift

> Call an app from Swift with a client generated from its bijection.lock contract

The Swift client is the `Bijection` library plus a package `bijection client
swift` generates for your app. The generated package holds a ref for every
exposed function, typed by its arguments and value, and a `connect` that pins
the app contract. It runs on macOS 13 and iOS 16 or later.

## Install

Generate the app's client package and add it to your Swift package. It
depends on the `Bijection` runtime, which SwiftPM resolves with it:

```swift Package.swift theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
dependencies: [.package(path: "../OrdersClient")],
targets: [.target(name: "Shop", dependencies: ["OrdersClient"])]
```

## Generate a client

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection client swift --out OrdersClient --name OrdersClient
```

`--name` is the Swift package and module name. The command reads the app's
exposed tree and refuses when the committed `bijection.lock` is stale: run
`bijection check --write-lock` and commit the lock first. Generate again when
the app's exposed functions change.

The package has:

* `App`, the tree of refs: `App.Orders.place` is the function at
  `orders.place`. Only functions with `allow` appear.
* a struct for each object argument and value, with its codec, and a
  `String`-backed enum for each set of string literals;
* `contract`, the `contract` line of `bijection.lock`, and `connect`, which
  pins it.

## Connect

```swift theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import OrdersClient

let client = connect(URL(string: "https://acme.bijection.app")!, .init(token: token))
```

Pass `token` for a fixed credential, or `tokenSource` (a `TokenSource`) to be
asked for the current token on every call and live connection. Leave both out
to call anonymously.

The generated `connect` sends the pinned contract with every call. A
installation whose contract differs refuses every call with `Conflict`, and the
message starts with `ContractStale`: generate the client again against the
deployed app.

For a dynamic tool, pass `.init(contract: .discover)` to the raw connector. A pinned client refuses a path absent from its contract map before sending it.

## Calls

```swift theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
let recent = await client.query(App.Orders.recent, .init(customer: "c-1"))
let placed = await client.mutate(App.Orders.place, .init(sku: "A-1", quantity: 2))
```

`query` runs a query once. `mutate` runs a mutation as one transaction. A
function without arguments takes `.init()`.

Every mutation has an identity, `once`. Leave it out and the client mints one
for the call. When a mutation answers `Unknown`, its reply was lost and it may
have committed: call it again with the same `once`. The same `once` with the
same arguments answers the original result, and with other arguments it
refuses `Invalid`.
An uncertain mutation carries its original request key in `Refusal.once`.

```swift theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
let once = UUID().uuidString
var result = await client.mutate(App.Orders.place, order, once: once)
if result.refused?.code == HostCode.unknown {
  result = await client.mutate(App.Orders.place, order, once: once)
}
```

## Frames

A frame method returns a new client and leaves the original unchanged:

| Method | Meaning |
| - | - |
| `client.under(.tag("access.finance"))` | Act under that label. `.member("access.tenant", "acme")`, `.and` and `.anyOf` build others. |
| `client.in(.branch("plan-2027"))` | Run in a branch, or read at `.version(v)`. |
| `client.at(date)` | Read at that valid instant. |

A committed mutation carries its `version`. Pass it as `seen` to a later
query, watch, mutation or trial to answer from state at least that new:

```swift theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
if case .ok(_, let version) = placed {
  let mine = await client.query(App.Orders.recent, .init(customer: "c-1"), seen: version)
}
```

## Results

Every verb answers `Bijection.Result<V>`: `.ok(value, version:)` or
`.refusal(Refusal)`. A refusal has a `code`, on a host code its `reason` (the
precise cause, such as `BudgetExhausted` under `Limit`), a `message` the
caller may read and, on `Forbidden`, the `guard` that refused. `Result` here is
`Bijection.Result`: qualify it where `Swift.Result` is also in scope.

```swift theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
switch placed {
case .ok(let order, _):
  show(order)
case .refusal(let refusal) where refusal.code == "OutOfStock":
  showOutOfStock(refusal.message)
case .refusal(let refusal):
  report(refusal.code, refusal.message, refusal.guard)
}
```

A code is one of the twelve host codes (`HostCode.unknown`, `.disallowed`,
`.forbidden`, `.invalid`, `.absent`, `.exists`, `.conflict`, `.erased`,
`.expired`, `.withdrawn`, `.limit`, `.failed`) or one of the codes the
function declares in `refuses`. Any other code from the host is folded into
its host code, and the message keeps the original code. `result.get()`
returns the value or throws the refusal.

## Watch

`watch` runs a query and keeps its value current. It is an `AsyncSequence`
of results:

```swift theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
let live = client.watch(App.Notes.list, .init())
for await notes in live {
  if case .ok(let list, _) = notes { render(list) }
}
```

Leave the loop or call `live.stop()` to end it. A client in another world or
at another instant reads once and ends. The live connection is the
installation's HTTP event stream through `URLSession` on iOS and macOS
alike; `ConnectOptions.live` takes another.

## Trial

`trial` runs a call in a discarded world and commits nothing:

```swift theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
let trial = await client.trial(App.Orders.place, order)
print(trial.result.refused?.guard ?? "allowed", trial.writes, trial.tasks)
```

`writes` lists each write the call would make (`verb`, `table`, `key`,
`before`, `after`), and `tasks` each task it would submit (`target`, `args`,
`due`). `validUntil` is the instant the answer is valid until (a call at the same
version committed before it is decided the same way), or nil when nothing
time-dependent bounds it.

## Values

| Bijection | Swift |
| - | - |
| `t.int` | `Int64` |
| `t.number` | `Double` |
| `t.decimal` | `DecimalValue` |
| `t.string`, keys, versions | `String` |
| `t.bytes` | `Data` |
| `t.date` | `DateComponents` (year, month, day) |
| `t.instant` | `Date` |
| `t.duration` | `Swift.Duration` |
| `t.maybe(x)` | an optional |
| lists, maps | arrays, `[String: T]` |
| other unions, `t.any` | `Value` |

A duration with years or months has no fixed length and decodes as an
`Invalid` refusal. An untyped call takes and answers `Value`s:
`client.query(QueryRef("notes.list"), .object([:]))`.

## Change entries

A query that returns `selection.changes` answers `Change<Fact>` entries:
`key`, `before` (nil on an insert), `after` (nil on a delete) and the
change's `version`.

## iOS

An iOS app uses the same `Bijection` package and the generated `connect`:
there is no separate mobile package. To sign in through an identity provider,
implement `AuthProvider` and pass `SignIn(provider:)` as `tokenSource`;
`login()`, `loginFromCache()`, `logout()` and `authState` drive it. `SignIn`
answers `Swift.Result`; the client's own is `Bijection.Result`, so qualify
one of them where both are in scope.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.