Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

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 dev running the List luna 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/luna

Add a package

Add an app folder beside the luna folder.

  • .env.local
  • app/
    • Package.swift
    • Sources/
      • ListApp/
        • main.swift
    • 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 app

See 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

Was this page helpful?