Using Claude with Swift | Getting Started with Foundation Models iOS Integration
Anthropic officially provides the ClaudeForFoundationModels Swift package for Apple's Foundation Models framework, allowing iOS/macOS apps to call Claude via the standard LanguageModelSession API. This article walks developers through everything from setup with Swift Package Manager to implementing streaming, structured output, and server-side tools.
目次 (14)
- Overview of Claude × Swift
- Overview of the ClaudeForFoundationModels Package
- Installation via Swift Package Manager
- Basic Usage — Quick Start
- Streaming Responses and Structured Output
- Streaming Responses
- Structured Output (@Generable)
- Enabling Server-Side Tools
- Authentication — Development API Keys and Production Proxies
- Development Environment (Direct API Key)
- Production Environment (Via Proxy)
- Error Handling and Choosing Between Claude and On-Device Models
- Current Limitations
- Summary
Overview of Claude × Swift
There are currently two main ways to use Claude from Swift.
- ClaudeForFoundationModels (Anthropic official): A Swift package that runs Claude as a server-side model on top of Apple's
FoundationModelsframework. The unifiedLanguageModelSessionAPI lets you transparently switch between on-device models and Claude. - Community Swift SDKs: Implementations that call the Messages API directly. Since Anthropic does not provide an official Swift client, you would use third-party libraries such as
SwiftClaude(GitHub, by GeorgeLyon, 73 stars).
Anthropic's current focus is the former, with official integration targeting iOS 27 / macOS 27 and later actively underway.
Overview of the ClaudeForFoundationModels Package
Anthropic and Apple collaborated during the WWDC 2026 season to add server-side language model support to the Foundation Models framework. Claude became the first partner model to launch.
- Unified API: Simply swap the model passed to
LanguageModelSessionto control both Apple on-device models and Claude with identical code. - Communication path: Requests travel directly from the device to Anthropic's servers; Apple does not access prompts or responses.
- Beta stage: Requires iOS 27 / macOS 27 / visionOS 27 / watchOS 27 and Xcode 27 (all developer betas).
Source: Anthropic official documentation "Apple Foundation Models" (https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/apple-foundation-models)
Installation via Swift Package Manager
Add a single dependency line to Package.swift.
dependencies: [
.package(
url: "https://github.com/anthropics/ClaudeForFoundationModels.git",
from: "0.1.0"
)
]
In Xcode, go to File > Add Package Dependencies… and enter the same repository URL to add the package. Import the following two lines in files where you use it.
import FoundationModels
import ClaudeForFoundationModels
Basic Usage — Quick Start
Create a ClaudeLanguageModel instance and pass it to LanguageModelSession. Everything after that works just like standard Foundation Models.
import FoundationModels
import ClaudeForFoundationModels
let model = ClaudeLanguageModel(
name: .sonnet4_6,
auth: .apiKey(ProcessInfo.processInfo.environment["ANTHROPIC_API_KEY"] ?? "")
)
let session = LanguageModelSession(model: model)
let response = try await session.respond(to: "東京の 4 日間旅行プランを提案して")
print(response.content)
Available model constants include .sonnet4_6 and .opus4_8. These correspond internally to Claude API model IDs and can be checked via the ClaudeModel type. You can also specify an effort level such as fixedEffort: .xhigh.
Streaming Responses and Structured Output
Streaming Responses
streamResponse(to:) returns cumulative snapshots rather than deltas. This makes it well-suited for incremental UI rendering.
let stream = session.streamResponse(to: "本日のトップニュースをまとめて")
for try await partial in stream {
print(partial.content)
}
Structured Output (@Generable)
Pass a type annotated with @Generable and the model will return type-safe output.
@Generable
struct Trip {
@Guide(description: "目的地都市") var destination: String
@Guide(description: "泊数") var nights: Int
}
let result = try await session.respond(to: "パリ旅行を計画して", generating: Trip.self)
print(result.content.destination) // "Paris"
print(result.content.nights) // 5
If the model's capabilities do not include structured output, LanguageModelError.unsupportedGenerationGuide is thrown. All compiled constants support structured output.
Enabling Server-Side Tools
Tools processed on Anthropic's infrastructure — such as web search and code execution — are configured via serverTools:.
let model = ClaudeLanguageModel(
name: .sonnet4_6,
auth: auth,
serverTools: [
.webSearch(maxUses: 5),
.codeExecution,
]
)
.webSearch supports access control via allowedDomains, blockedDomains, and maxUses. Tool execution results are recorded in the transcript as ClaudeServerToolSegment. Since server-side tools are configured per ClaudeLanguageModel instance, create multiple model instances if you need different tool sets for different conversations.
Authentication — Development API Keys and Production Proxies
Development Environment (Direct API Key)
ClaudeLanguageModel(name: .sonnet4_6, auth: .apiKey("sk-ant-..."))
Embedding an API key in an app binary risks extraction. Limit this to development use only, and always use a proxy from TestFlight onward.
Production Environment (Via Proxy)
The recommended setup has your own backend attach x-api-key and forward requests to Anthropic's servers.
ClaudeLanguageModel(
name: .sonnet4_6,
auth: .proxied(headers: ["X-App-Token": "your-app-token"]),
baseURL: URL(string: "https://api.yourapp.com/claude")!
)
The proxy receives requests in the standard Messages API format, adds the x-api-key header, and forwards them to https://api.anthropic.com.
Error Handling and Choosing Between Claude and On-Device Models
Claude API errors are mapped to Foundation Models' LanguageModelError. Apple recommends a pattern of falling back to an on-device model when rate-limited.
do {
let response = try await session.respond(to: prompt)
print(response.content)
} catch ClaudeError.missingCredential {
// API key not set — guide user to settings
} catch LanguageModelError.rateLimited {
// Rate limit exceeded — fall back to on-device model
let fallback = LanguageModelSession(model: SystemLanguageModel.default)
let res = try await fallback.respond(to: prompt)
print(res.content)
} catch LanguageModelError.contextSizeExceeded {
// Context length exceeded
} catch {
// Network errors, etc.
}
The decision criteria are clear: choose Claude when you need extended context, frontier-level reasoning, or server-side tools; choose the on-device model when speed, privacy, or offline operation takes priority.
Current Limitations
Because ClaudeForFoundationModels prioritizes compliance with Foundation Models protocols, some features are unavailable.
- Manual control of prompt caching (auto-applied only)
- Stop sequence specification
- Batch processing
- Files API
- Token counting
- Beta headers
If you need these features, consider calling the Messages API directly or routing through the ant CLI.
Summary
The ClaudeForFoundationModels package is a framework targeting iOS 27 / macOS 27 beta, but because it integrates fully with Apple's LanguageModelSession API, the learning curve for adding Claude to existing Foundation Models code is very low. With key features including streaming, structured output, and web search all available, starting your implementation now will let you ship smoothly when iOS 27 officially releases.
Sources
- Anthropic official documentation "Apple Foundation Models": https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/apple-foundation-models
- ClaudeForFoundationModels GitHub repository: https://github.com/anthropics/ClaudeForFoundationModels
- Anthropic official "Client SDKs and Libraries": https://platform.claude.com/docs/en/api/client-sdks