Swift quickstart
Add an item to a list and read the list back from a Swift program with the Luna client.
At the end of this page you have a Swift program that adds an item to a List luna and reads the list back. It uses LunaClient from the Luna Swift package and runs on a Mac.
Prerequisites
- The Quickstart done, with
luna devrunning theListluna and its URL and key in.env.local. - Xcode 16 or later, on macOS 14 or later.
Write out the Swift SDK
luna sdk swift app/vendor/lunaAdd a package
Add an app folder beside the luna folder.
- .env.local
- app/
- Package.swift
- Sources/
- ListApp/
- main.swift
- ListApp/
- vendor/
- luna/
- luna/
- luna.config.ts
- lunas/
- list.ts
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "ListApp",
platforms: [.macOS(.v14)],
dependencies: [.package(path: "vendor/luna")],
targets: [
.executableTarget(name: "ListApp", dependencies: [.product(name: "Luna", package: "luna")]),
]
)Write the program
import Foundation
import Luna
struct Item: Codable, Sendable {
let id: Int
let text: String
}
let env = ProcessInfo.processInfo.environment
let client = LunaClient(ClientOptions(url: URL(string: env["LUNA_URL"]!)!, key: env["LUNA_KEY"]))
let list = client.luna("List", "weekend")
try await list.mutate("add", ["text": "bread"])
let items = try await list.read("all", as: [Item].self)
for item in items { print(item.text) }
client.close()Run it
set -a && source .env.local && set +a && swift run --package-path appSee the result
The program adds bread to the list named weekend, then prints each item of that list.
bread
Run it again and the list holds two items. In an iOS or macOS app project, add the same vendor/luna folder in Xcode with File > Add Package Dependencies > Add Local.
Next steps
- Call lunas from Swift covers live queries in SwiftUI, writes and errors.
- Generate a typed client replaces handler names and JSON with Swift methods and types.
- Swift client lists every type and method of the package.