• Start

Languages

/

Swift

Getting started

In this section, you will learn how to connect to SurrealDB and run your first query using the Swift SDK.

This guide covers defining a model, connecting to SurrealDB, authenticating, and running your first queries with the Swift SDK. Make sure you have installed the SDK first.

The @SurrealModel macro generates SurrealModel conformance, the surrealTable name, and a type-safe Fields namespace used to build predicates.

import SurrealDB

@SurrealModel("person")
struct Person: Codable, Sendable {
let id: String?
let name: String
let age: Int
}

Create a client for your endpoint and connect. The HTTP client is the simplest starting point; for live queries you will need the WebSocket client instead.

let client = try SurrealHTTPClient(endpoint: "http://localhost:8000")
try await client.connect()
defer { Task { await client.close() } }
let tokens = try await client.signin(.root(username: "root", password: "root"))
try await client.use(namespace: "myapp", database: "mydb")
// Create a record
let created: [Person] = try await client.create(
Person(id: nil, name: "Ada", age: 30)
)

// Select all records of a table
let people = try await client.select(Person.self)

// Select with a type-safe predicate
let adults = try await client.select(
Person.self,
where: Person.Fields.age >= 18,
limit: 20,
start: 0
)

Continue with the rest of the documentation:

Was this page helpful?