Skip to content

iOS & macOS Quickstart

This guide shows how to add the Swift AI SDK to an iOS or macOS app, call models, and stream results into your UI.

In Xcode: File → Add Package Dependencies…

Set environment variables in your scheme or via a secure configuration:

OPENAI_API_KEY=sk-...

The default provider shortcuts (e.g., openai) read standard env vars automatically.

import SwiftAISDK
import OpenAIProvider
let result = try await generateText(
model: openai("gpt-4o"),
prompt: "Hello from Swift!"
)
print(result.text)
import SwiftUI
import SwiftAISDK
import OpenAIProvider
@MainActor
final class ChatViewModel: ObservableObject {
@Published var output: String = ""
@Published var isLoading = false
func send(_ prompt: String) {
isLoading = true
output = ""
Task {
do {
let stream = try streamText(
model: openai("gpt-4o"),
prompt: prompt
)
for try await delta in stream.textStream {
output += delta
}
} catch {
output = "Error: \(error)"
}
isLoading = false
}
}
}
struct ChatView: View {
@StateObject var vm = ChatViewModel()
@State var input = "Write a haiku about vectors"
var body: some View {
VStack(alignment: .leading) {
TextEditor(text: $input).frame(height: 120)
Button(vm.isLoading ? "Streaming…" : "Send") { vm.send(input) }
ScrollView { Text(vm.output).monospaced() }
}
.padding()
}
}
struct EchoPayload: Codable, Sendable {
let message: String
}
let echo = tool(
description: "Echo back the input data",
inputSchema: EchoPayload.self
) { payload, _ in
EchoPayload(message: payload.message.uppercased())
}
let result = try await generateText(
model: openai("gpt-4o"),
tools: ["echo": echo.eraseToTool()],
prompt: "Call echo with {\"message\":\"Hello!\"}"
)

Keep long‑running work off the main actor; UI updates should be marshalled on the main thread.