---
title: Swift client
description: Every public type, initialiser and method of the Luna Swift package, for iOS, macOS and the other Apple platforms.
related:
  - /clients/swift-quickstart
  - /clients/call-lunas-from-swift
  - /clients/generate-a-typed-client
---

The `Luna` Swift package calls lunas from an app on iOS 17, macOS 14, tvOS 17, watchOS 10, visionOS 1 and later. It follows the same model as [createClient](/sdk/create-client): live queries, optimistic writes, reconnecting, pushes, streams and queued writes.

```swift app/Groceries.swift
import Foundation
import Luna

struct Item: Codable, Sendable { let id: Int; let text: String }

@MainActor
func addMilk() async throws {
    let client = LunaClient(ClientOptions(url: URL(string: "<LUNA_URL>")!, key: "<LUNA_KEY>"))
    let list = client.luna("List", "groceries")

    let items = list.query("all", as: [Item].self)
    let subscription = items.subscribe { print(items.state.data ?? []) }

    try await list.mutate("add", ["text": "milk"])
    subscription.cancel()
}
```

## Reference

Every type that holds state is `@MainActor`. Call it from the main actor.

### ClientOptions

`ClientOptions(url:key:)` makes the options. Set the other fields on a `var` before you pass it to `LunaClient`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `url` | `URL` | - | The environment's URL, the LUNA_URL in .env.local. |
| `key?` | `String?` | - | A publishable key. It reaches public luna types only. |
| `token?` | `String?` | - | A secret token, sent as Authorization: Bearer. For your own servers and tools, never in an app. |
| `headers?` | `[String: String]` | `[:]` | Extra request headers. |
| `params?` | `(@Sendable () async throws -> [String: String])?` | - | Query parameters for each new connection, which onBeforeConnect reads. Asked again on every reconnect. |
| `keepAlive?` | `Duration` | `.seconds(10)` | How long a query nobody watches stays live and cached. |
| `settle?` | `Duration` | `.seconds(1)` | How long a confirmed write stays laid over the queries of other lunas. Queries of the write's own luna get four times as long. |
| `callTimeout?` | `Duration` | `.seconds(30)` | How long a call may take, including the wait to connect. |
| `multiplex?` | `Bool` | `true` | One WebSocket for all of the client's lunas. With false, one each. |
| `store?` | `(any ClientStore)?` | - | Where query results and queued writes are kept between runs. Use one per account. |
| `optimistic?` | `[String: QueuedOptimistic]` | `[:]` | Optimistic updates for queued writes, by name. |
| `transport?` | `@MainActor @Sendable (URL, [String: String]) -> any LunaTransport` | - | Makes each WebSocket. Tests replace it. |
| `fetch?` | `@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse)` | - | Makes each stream read. Tests replace it. |

### LunaClient

| Prop | Type | Default | Description |
| - | - | - | - |
| `init(_ options:)?` | `LunaClient` | - | Makes a client. With a store, it reads back saved writes and starts sending them. |
| `luna(_ type:, _ key...)?` | `LunaHandle` | - | One luna, by its type and key values, such as luna("List", "groceries"). |
| `index(_ name:, partition:)?` | `IndexHandle` | - | One partition of an index, read live. |
| `writes?` | `[QueuedWrite]` | - | The queued writes that wait or failed, oldest first. |
| `subscribeWrites(_ fn:)?` | `Subscription` | - | Hears every change to the queue. |
| `resumeWrites()?` | `Void` | - | Sends the queue again after it stopped for a sign-in that ran out. |
| `retryWrite(_ id:)?` | `Void` | - | Puts a failed write back in the queue. |
| `discardWrite(_ id:)?` | `Void` | - | Drops a failed write. |
| `wipe()?` | `async` | - | Empties the store and the queue, for when someone signs out. |
| `close()?` | `Void` | - | Closes every connection. The client cannot be used after. |
| `options?` | `ClientOptions` | - | The options the client was made with. |

### LunaHandle

| Prop | Type | Default | Description |
| - | - | - | - |
| `query(_ handler:, _ args:, as:)?` | `LiveQuery<T>` | - | A live query of a query handler, decoded as T. |
| `mutate(_ handler:, _ args:, timeout:, optimistic:)?` | `async throws -> JSON` | - | Calls a handler. optimistic changes what queries show until the write is in. |
| `mutate(_ handler:, _ args:, returning:, timeout:, optimistic:)?` | `async throws -> R` | - | The same, with the result decoded. |
| `read(_ handler:, _ args:, timeout:)?` | `async throws -> JSON` | - | One answer from a handler, not followed. |
| `read(_ handler:, _ args:, as:, timeout:)?` | `async throws -> R` | - | The same, with the result decoded. |
| `response(_ handler:, _ args:, timeout:)?` | `async throws -> HTTPResult` | - | Calls a handler that answers with a Response: its status, headers and body. |
| `iterate(_ handler:, _ args:)?` | `AsyncThrowingStream<JSON, Error>` | - | What a streaming handler yields, as it yields it. Leaving the loop stops the handler. |
| `connectionStatus?` | `ConnectionStatus` | - | The connection's state now. |
| `onConnectionChange(_ fn:)?` | `Subscription` | - | Hears each change of state and keeps the connection open. |
| `enqueue(_ handler:, _ args:, optimistic:)?` | `throws -> QueuedResult` | - | Queues a write that survives restarts. optimistic names an update in ClientOptions.optimistic. |
| `on(_ push:, as:, _ fn:)?` | `Subscription` | - | Hears a push, decoded as T. A push that does not decode is skipped. |
| `stream(_ name:, as:, offset:, limit:)?` | `StreamReader<T>` | - | Reads a stream as it grows. offset is "-1" and limit 1000 unless given. |
| `observe(_ handler:, _ args:, as:)?` | `ObservedQuery<T>` | - | A live query as an observable value, for SwiftUI. |
| `observeConnection()?` | `ObservedConnection` | - | The connection as an observable value. |
| `observeStream(_ name:, as:, offset:, limit:)?` | `ObservedStream<T>` | - | A stream as an observable value. |

### LiveQuery and QueryState

| Prop | Type | Default | Description |
| - | - | - | - |
| `state?` | `QueryState<T>` | - | The latest state. |
| `subscribe(_ fn:)?` | `Subscription` | - | Hears every change and keeps the query live while the subscription is held. |
| `updates?` | `AsyncStream<QueryState<T>>` | - | Each state as it changes, starting with the current one. |
| `QueryState.status?` | `.loading \| .ready \| .error` | - | .ready once there is data. .error when the first run failed. |
| `QueryState.data?` | `T?` | - | The confirmed result, with pending writes laid over it. |
| `QueryState.error?` | `LunaError?` | - | The latest run's failure. data stays as it was. |
| `QueryState.stale?` | `Bool` | - | The connection dropped, or the result is a saved one, so data may be behind. |

### LocalStore

What an `optimistic` closure receives.

| Prop | Type | Default | Description |
| - | - | - | - |
| `get(_ query:)?` | `T?` | - | A query's value as of the writes before this one. nil when it is not loaded. |
| `set(_ query:, _ value:)?` | `Void` | - | Replaces what a query shows while this write is pending. |
| `update(_ query:, _ fn:)?` | `Void` | - | set from the current value. Does nothing when the query is not loaded. |

### Subscription and ConnectionStatus

`Subscription.cancel()` ends what it was returned for. Releasing the subscription ends it too, so keep it while you need it.

`ConnectionStatus` is `.connecting`, `.open`, `.reconnecting` or `.closed`.

### StreamReader and StreamState

| Prop | Type | Default | Description |
| - | - | - | - |
| `state?` | `StreamState<T>` | - | What has been read so far. |
| `subscribe(_ fn:)?` | `Subscription` | - | Hears new entries and keeps reading. |
| `StreamState.entries?` | `[T]` | - | What has been read, oldest first, at most limit of them. |
| `StreamState.offset?` | `String` | - | Where reading goes on from. |
| `StreamState.upToDate?` | `Bool` | - | The last read reached the end of the stream. |
| `StreamState.error?` | `LunaError?` | - | The last read's failure. |

### IndexHandle

Options are JSON with the same names as in TypeScript. See [IndexHandle](/sdk/index-handle).

| Prop | Type | Default | Description |
| - | - | - | - |
| `find(_ options:, as:)?` | `LiveQuery<[Row]>` | - | Rows that match: where, orderBy and limit. |
| `count(_ options:)?` | `LiveQuery<Int>` | - | How many rows match: where. |
| `groupBy(_ options:, as:)?` | `LiveQuery<[Row]>` | - | Rows grouped: by, where, sum, min, max and limit. |
| `search(_ text:, where:, limit:, match:, prefix:, as:)?` | `LiveQuery<[SearchHit<Row>]>` | - | Full-text search, best first. match is "all" unless given. |
| `nearest(_ column:, to:, k:, where:, as:)?` | `LiveQuery<[NearestHit<Row>]>` | - | The rows whose vector column is nearest, nearest first. |
| `SearchHit?` | `{ row: Row, score: Double }` | - | A row search found. A higher score is a better match. |
| `NearestHit?` | `{ row: Row, distance: Double }` | - | A row nearest found. A smaller distance is nearer. |

### Observable values

Each is `@Observable`. Hold one in `@State` and the view follows it. It stays live for as long as it is held.

| Prop | Type | Default | Description |
| - | - | - | - |
| `ObservedQuery(_ query:)?` | `state, data, status, error, stale` | - | A live query. |
| `ObservedConnection(_ luna:)?` | `status` | - | The connection to a luna. |
| `ObservedStream(_ reader:)?` | `state, entries` | - | A stream of a luna. |

### JSON

The value arguments and results are made of. It is `Codable`, `Hashable` and `Sendable`, and Swift literals make one, such as `["text": "milk"]`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `cases?` | `.null, .bool, .int, .double, .string, .array, .object` | - | One case per kind of JSON value. Whole numbers are Int64. |
| `init(encoding:)?` | `throws` | - | Any Encodable value as JSON. |
| `decode(as:)?` | `throws -> T` | - | This value as a Decodable type. |
| `subscript(_ key:)?` | `JSON?` | - | A field of an object. nil for anything else. |

### LunaError, HTTPResult and HTTPError

| Prop | Type | Default | Description |
| - | - | - | - |
| `LunaError.code?` | `String` | - | Luna's code, such as Closed or Timeout, or the luna's own. |
| `LunaError.message?` | `String` | - | What went wrong. |
| `LunaError.data?` | `JSON?` | - | What came with the error, such as a declared error's data. |
| `LunaError.status?` | `Int?` | - | For a refused connection, the HTTP status. 403 when onBeforeConnect refused. |
| `LunaError(code:message:data:status:)?` | `init` | - | Makes one. |
| `HTTPResult.status?` | `Int` | - | The Response's status. |
| `HTTPResult.headers?` | `[String: String]` | - | Its headers, names in lower case. |
| `HTTPResult.body?` | `Data` | - | Its body, as sent. |
| `HTTPResult.text?` | `String` | - | The body as text. |
| `HTTPResult.json()?` | `throws -> JSON` | - | The body as JSON. |
| `HTTPError.result?` | `HTTPResult` | - | A Response with a status of 400 or above, thrown by mutate and read. |
| `HTTPError.status?` | `Int` | - | Its status. |

### ClientStore and DiskStore

`ClientStore` is a protocol with `get(_:)`, `set(_:_:)`, `delete(_:)`, `keys(prefix:)` and `compact()`. Each method but `compact()` may throw. `compact()` runs once at startup and does nothing unless you give it a body.

| Prop | Type | Default | Description |
| - | - | - | - |
| `DiskStore(account:)?` | `throws` | - | A folder for one account under the app's Application Support directory. |
| `DiskStore(directory:)?` | `throws` | - | A folder you choose. It is made if it does not exist. |
| `directory?` | `URL` | - | Where the files are. |

`DiskStore` keeps one file per key, and keeps the 2,000 query results saved most recently.

### QueuedWrite, QueuedResult and QueuedOptimistic

| Prop | Type | Default | Description |
| - | - | - | - |
| `QueuedWrite?` | `id, path, handler, args, status, error` | - | A write that waits or failed. status is .pending or .failed. |
| `QueuedResult.id?` | `String` | - | The write's id, also its idempotency key. |
| `QueuedResult.value()?` | `async throws -> JSON` | - | What the handler returned, once it has run. |
| `QueuedOptimistic?` | `@MainActor @Sendable (LocalStore, LunaHandle, JSON) -> Void` | - | An optimistic update for a queued write: the store, the luna and the write's arguments. |

### LunaTransport

The protocol a WebSocket meets for `ClientOptions.transport`: `onMessage`, `onClose`, `send(_:)` and `close(code:)`. The default uses `URLSession`.

## Good to know

- Writes made on one connection run one at a time, in the order sent. A write whose connection dropped throws `Closed`, and may or may not have happened.
- `close()` fails the promises of queued writes with `Closed`. The writes stay in the store and go when a new client starts.
- The package has no typed wrappers of its own. `luna generate` writes them for your luna types.
- Swift has no `connect`. Messages to `onMessage` need the TypeScript [connect](/sdk/connect).

## Examples

### Show a write at once

```swift app/Groceries.swift
try await list.mutate("add", ["text": "milk"]) { local in
    local.update(items) { $0 + [Item(id: -1, text: "milk")] }
}
```

### Follow a query in SwiftUI

```swift app/GroceriesView.swift
import Luna
import SwiftUI

struct GroceriesView: View {
    @State private var items: ObservedQuery<[Item]>

    init(list: LunaHandle) {
        _items = State(initialValue: list.observe("all", as: [Item].self))
    }

    var body: some View {
        List(items.data ?? [], id: \.id) { Text($0.text) }
    }
}
```

### Follow a query without SwiftUI

```swift app/Groceries.swift
for await state in list.query("all", as: [Item].self).updates {
    print(state.data ?? [], state.stale)
}
```

### Queue writes that survive a restart

```swift app/Client.swift
var options = ClientOptions(url: URL(string: "<LUNA_URL>")!, key: "<LUNA_KEY>")
options.store = try DiskStore(account: "account-42")
options.optimistic = [
    "addItem": { local, luna, args in
        let text = (try? args["text"]?.decode(as: String.self)) ?? ""
        local.update(luna.query("all", as: [Item].self)) { $0 + [Item(id: -1, text: text)] }
    },
]
let client = LunaClient(options)
try client.luna("List", "groceries").enqueue("add", ["text": "eggs"], optimistic: "addItem")
```

### Hear a push and read a stream

```swift app/Room.swift
struct Said: Codable, Sendable { let text: String }

let room = client.luna("Room", "lobby")
let pushes = room.on("said", as: Said.self) { print($0.text) }
let reader = room.stream("said", as: Said.self, offset: "now", limit: 100)
let reading = reader.subscribe { print(reader.state.entries.map(\.text)) }
```

### Search an index

```swift app/Cards.swift
struct Card: Codable, Sendable { let title: String; let done: Bool; let board: String }

let cards = client.index("BoardCards", partition: "b1")
let open = cards.find(["where": ["done": false], "orderBy": "title"], as: Card.self)
let hits = cards.search("mil", prefix: true, as: Card.self)
```

### Tell errors apart

```swift app/Groceries.swift
do {
    try await list.mutate("add", ["text": "milk"])
} catch let e as LunaError {
    print(e.code, e.message)
} catch let e as HTTPError {
    print(e.status)
}
```
