Swift
Build Jazz apps in Swift: an end-user client of your app, with typed bindings generated from your app's schema.For apps: run your backend in TypeScript.
A Swift app is an end-user client of your app. It uses the same schema as every other language,
with typed bindings generated from your app's schema with npx jazz-tools generate, signs a user
in, and syncs through your backend's Jazz endpoint. The Swift package wraps the Jazz core, built from Rust, through UniFFI. Calls are
async, and subscriptions are AsyncSequences.
Jazz for Swift is for macOS and iOS apps (Swift 6.0 or newer, Xcode 16 or newer; macOS 13 and iOS
16 or newer). Each release's package runs its tests on macOS and on an iPhone simulator against the
prebuilt core, and the StagePlan SwiftUI example (examples/stage-plan/apps/swiftui) is built for
macOS and UI-tested on the iPhone simulator.
Install
Add the package https://github.com/garden-co/jazz-swift at version 2.0.0-alpha.66 with the Jazz
product: in Xcode under File → Add Package Dependencies…, or in your Package.swift:
Package.swiftdependencies: [.package(url: "https://github.com/garden-co/jazz-swift", exact: "2.0.0-alpha.66")],targets: [.target(name: "MyApp",dependencies: [.product(name: "Jazz", package: "jazz-swift")],path: ".",sources: ["JazzApp.swift", "Sources/MyApp"]),]
That's all: the package brings the Jazz core prebuilt, and SwiftPM checks it against the checksum the release pins. There's nothing to build besides your app.
Swift on Linux has no prebuilt core: if you need it, ask on Discord.
Generate the bindings
The bindings are generated from your app's schema with npx jazz-tools generate. Write the schema
and permissions in a schema.ts (see Defining Tables and
Declarative Permissions) beside a Package.swift that uses the Jazz
product (no package.json is needed) and run it there: it writes jazz.app.json,
jazz.permissions.json and JazzApp.swift next to them.
npx jazz-tools generate # writes the app files and JazzApp.swiftnpx jazz-tools generate --check # in CI: fails if any of them is stale
A Swift client of an app whose schema lives elsewhere (its TypeScript backend's, say) gets a
two-line schema.ts that re-exports it, as StagePlan's Swift example does:
export { schema, permissions } from "../react-localfirst/schema";
Detection picks Swift from the Package.swift; --lang swift selects it explicitly. Edit only
schema.ts: the JSON files and JazzApp.swift are generated, so commit them and regenerate after
each schema change. Run generate with npx: the standalone jazz-tools binary refuses to write
beside a schema.ts, though its generate --check still works.
Commit JazzApp.swift and add it to your target's sources. Everything in it sits inside
public enum JazzApp, so a table's names never hide Swift's own types: StagePlan's tasks table
gives JazzApp.Task, not Task. For each table, it gives you:
- a
Codablerow struct (JazzApp.Task), with lowerCamelCase properties; JazzApp.NewTask, for inserts. Columns that may be left out are optional and default tonil;JazzApp.TaskPatch, for updates. Each column is.unchangedor.set(value);- a namespace (
JazzApp.tasks) withquery()and typed columns, for filters andorderBy; - a Swift enum for each enum column (
JazzApp.TaskStatus).
JazzApp.open(_:) opens the app from the jazz.app.json the file embeds.
Open the app
The app syncs through your app's Jazz endpoint (its backend's createJazz handler, never the sync
server itself), signed in with a device account or with your own sign-in's bearer tokens:
Sources/StagePlan/DocsSnippets.swift// An end user's client syncs through your app's Jazz endpoint (its// backend's handler). Sign in with a device account, whose key you// keep in the keychain, or with your own sign-in's bearer token.let auth: Jazz.Auth =if let deviceKey {.deviceKey(deviceKey) // from Jazz.generateDeviceKey()} else {.bearer { _ in try await MySignIn.currentToken() }}let jazz = try await JazzApp.open(.client(appId: appId, serverUrl: endpoint, auth: auth, storage: .memory))for try await state in jazz.session {if case .signedIn(let user) = state {print("signed in as", user.account)break}}
jazz.session yields .signedIn(user), .expired or .signedOut each time the session changes.
jazz.syncStatus() and jazz.syncChanges report the link (.connected, .offline(reason:…), …),
pending uploads and rejections, as TypeScript's SyncStatus. refresh() asks your token provider
again, link(bearer:) links a device account to your sign-in, and signOut() signs out and closes
the app. .local() opens a client without a server.
Before the process exits, call try await jazz.close(). It ends every live watch and
subscribe loop with JazzError.closed.
The Reading and Writing pages have a Swift
tab for each example. examples/stage-plan/apps/swift-cli in the repository is a complete
command-line client of StagePlan: it signs in with a device account, whose key it keeps in a file
only its user can read, or with a bearer token, and creates a show, lists, adds and moves tasks.
A device key is the account: keep it as a password in the Keychain. The Jazz Swift package has no helper for that yet.
Sessions
A session follows who is signed in, as TypeScript's JazzSession, and hands out the client of the
user signed in now. Start it as a device account (a guest who needs no sign-in), from your sign-in's
bearer token, or signed out.
In SwiftUI, JazzRoot does the rest, as <JazzProvider> does in React. It shows your views with the
signed-in user's client, signedOut while no one is signed in, and rebuilds the views when the user
changes; @JazzAll is a live query, like useAll:
@mainstruct MyApp: App {let session = JazzApp.session(appId: appId, serverUrl: "https://myapp.example/jazz",bearer: { _ in try await MySignIn.currentToken() }) // nil while signed outvar body: some Scene {WindowGroup {JazzRoot(session) { TasksView() } signedOut: { SignInView() }}}}struct TasksView: View {@JazzAll(JazzApp.tasks.query().orderBy(JazzApp.tasks.rank)) var tasks@Environment(\.jazz) var jazz // the signed-in user's client, like useDb@Environment(\.jazzSession) var session // user, status, signOut(), like useJazzSessionvar body: some View {List(tasks, id: \.id) { Text($0.title) }}}
Outside SwiftUI, try await session.client() waits while the session starts and returns the
signed-in user's client, and session.clients gives the next one each time the user changes, and
nil on sign-out (TypeScript's followDb):
Sources/StagePlan/DocsSnippets.swift// A session follows who is signed in: a device account (a guest)// until your sign-in names a user, who takes the guest's account// over if they have none yet. Call `session.refresh()` when your// sign-in changes.let session = JazzApp.session(appId: appId, serverUrl: endpoint,bearer: { _ in try await MySignIn.currentToken() }, // nil while signed outstart: .device, dataDir: dataDir)// The signed-in user's client, once the session is ready (it throws// .noUser if no one is). `session.clients` gives the next one each// time the user changes, and nil on sign-out.let jazz = try await session.client()
client() throws JazzError.noUser while no one is signed in, and a client kept past a change of
user throws JazzError.replaced. session.snapshots yields each SessionSnapshot (status,
user, clientEpoch, error and recovery), and ends with JazzError.closed when the session
closes.
When your sign-in changes, call session.refresh(): the session asks bearer again and follows
the user it names (nil: signed out). With linkGuest (the default, as TypeScript), a user who has
no account yet takes over the device account signed in before; with linkGuest: false, call
linkDeviceAccount() for that. createDeviceAccount(), restoreDeviceAccount(key:),
reopenDeviceAccount(), exportDeviceKey(), signOut() (the session stays open, signed out),
retry() (as recovery says) and close() complete it. Each account's store is under
dataDir/<account>/, and the device account's key in dataDir/device.key.
Computed fields and transforms
If your schema declares computed fields or transforms, the bindings declare a
JazzApp.Computed protocol. It has one method per computed field (tasksPriority(score:)) and a
View/Stored pair per transform (isoDateView(_:), isoDateStored(_:)).
JazzApp.open(_:computed:) takes your implementation, so a missing method is a compile error:
struct AppComputed: JazzApp.Computed {func tasksPriority(score: Int) -> JazzApp.TaskPriority { score > 5 ? .high : .low }func isoDateView(_ stored: Date) -> String { ISO8601DateFormatter().string(from: stored) }func isoDateStored(_ view: String) -> Date { ISO8601DateFormatter().date(from: view)! }}let jazz = try await JazzApp.open(config, computed: AppComputed())
Rows hold the computed values and the view form of transformed columns. Inserts and patches take the view form and write the stored one. Filters on a transformed column compare stored values.
SwiftUI and errors
On Apple platforms (macOS 14, iOS 17), @JazzAll(query) (see Sessions) keeps a
view's rows current, and $tasks is its JazzQuery, for isLoading and error. Without
JazzRoot, put a client in the environment yourself with .environment(\.jazz, client), or hold a
JazzQuery directly:
@State var tasks = JazzQuery(jazz, JazzApp.tasks.query().orderBy(JazzApp.tasks.rank))// tasks.rows, tasks.isLoading, tasks.error
Every call throws a JazzError (catch it with catch let error as JazzError). The cases are
refused (validation, permissions or not supported yet), io, closed, decoding,
cancelled (the calling task was cancelled), permissionDenied (your backend's permissions
refused it, seen when waiting for the global tier), notSupported, conflict (a serializable
transaction lost to another write: retry it), and for a JazzSession's clients replaced and
noUser.
Relations, transactions and tiers
Each relation is a row property, filled when the query includes it and nil otherwise:
JazzApp.tasks.query().include(JazzApp.tasks.show) fills task.show. A relation narrows like a
query: JazzApp.shows.tasks.orderBy(JazzApp.tasks.rank).limit(3), plus a nested .include(…) or
.required(). query.select(columns…) reads only some columns into a Decodable type of yours,
with jazz.all(selection, as: MyType.self).
jazz.transaction(commit:) { tx in … } runs a mergeable transaction, as TypeScript's
db.transaction: it commits when the closure returns, rolls back when the closure throws, and
rethrows that error. Its writes merge with concurrent ones, so its commit is never a conflict.
jazz.serializableTransaction(commit:) { tx in … } is TypeScript's db.serializableTransaction:
the server accepts it only if nothing it read changed meanwhile, else it throws
JazzError.conflict. Reads take a
tier: (.local, .localFirst, .remote), and so do writes (.local, .global);
jazz.waitForSync(.global) waits until everything written so far has reached the server.
Mergeable text and permission advice
A text-merge column ("merge": "text", like StagePlan's tasks.notes) reads as a plain String?.
To edit it so that concurrent edits merge instead of overwriting each other, use a JazzText
handle:
Sources/StagePlan/DocsSnippets.swift// Edits of a text-merge column (`"merge": "text"`) merge with others'// changes instead of replacing the whole value.let notes = try await jazz.text(task, JazzApp.tasks.notes)// Positions are String.Index of `notes.current`.try await notes.insert("Bring gaffer tape. ", at: notes.current.startIndex)if let bring = notes.current.range(of: "Bring") {try await notes.replace(bring, with: "Pack")}// From a UITextView: `notes.replace(range, with: text)` takes its NSRange.
Positions are Swift's own: String.Index and Range<String.Index> of notes.current
(notes.current.range(of: "draft"), say), so an edit can't land inside a character. Take them from
current just before the edit: another string's index is taken at its UTF-8 offset. From a
UITextView or NSAttributedString, pass their NSRange (UTF-16) to notes.replace(range, with:)
as it is, even when it splits a character (a backspace removing one combining mark);
replace(utf16:with:) takes raw UTF-16 offsets. A UTF-16 position inside a surrogate pair is
refused.
notes.changes yields the merged text each time the row changes. Lower level, jazz.edit(id, patch, edits: [.text(…), .splice(…), .jsonSet(…)]) makes several partial edits as one write.
jazz.canInsert(newRow), canRead, canUpdate and canDelete ask the app's permissions before
you try. They return true, false, or nil when there's nothing to ask, such as no server.
Hops, history and uploads
query.hopTo(JazzApp.tasks.show)reads the rows a relation leads to. The hop takes its ownwhere,orderBy,limitandoffset, and hops on with.hopTo(…).query.gather(JazzApp.nodes.parent, maxDepth: 5)reads rows along a relation of a table to itself.Union(q1, q2)reads every arm's rows; a row two arms match comes twice.query.history(), read withjazz.all, gives every version the server accepted, asVersion(row:transactionId:acceptedAt:).query.includeDeleted()reads deleted rows too;jazz.restore(T.self, id:)brings one back.jazz.upsert(id, newRow)writes a row with a given id.jazz.upload(newRow, column:, from: chunks)streams a large text or bytes value in from anAsyncSequence<Data>, andselect(parts: column.part(0..<4096, in: .bytes))reads it back in pages.
Not supported yet
Not supported yet:
- watchOS, tvOS and visionOS: they aren't built (the Jazz core's Rust targets for them are tier 3).
- Linux: there's no prebuilt core. Ask on Discord if you need it.
- A SwiftUI
BindingforJazzText. - Running a backend in Swift (publishing permissions, acting for users) or serving the app's Jazz endpoint: run your backend in TypeScript.
- Keychain (or file) storage for device keys: keep the key from
Jazz.generateDeviceKey()with your own code. - Anonymous (guest) users, as in TypeScript.
- Subscribing to history queries.
- Parts of large values inside includes: parts are for root queries.
offsetin an include, andrequiredon reverse relations or optional references.- Payload enums, nested rows and other column types the bindings can't type: they're refused when generating.
- Non-finite floats (
NaN, infinities) read back asnull. In aDoublecolumn that fails to decode. In a nullableDouble?column, it silently reads asnil. - Positions in subscription deltas:
subscribedeltas carry none, andwatchre-sorts its rows locally by the query'sorderBy.
A write that the server's permissions refuse doesn't throw by default. Writes are local-first, so
it stays in the local store and never syncs. Write with tier: .global (or call
waitForSync(.global)) to get JazzError.permissionDenied instead, or follow
jazz.mutationErrors (TypeScript's onMutationError), which reports each refused write nothing
waited on.
jazz.disconnect() leaves the server while local reads and writes go on, and jazz.reconnect()
resumes sync. jazz.deleteClientStorage() rolls back open transactions, closes the app and deletes its local
store (writes the server hasn't accepted are lost). While another open app holds the same dataDir,
it throws JazzError.refused and the app stays open (its open transactions are still rolled back). The session, syncChanges and mutationErrors streams end with
JazzError.closed when the app closes.