moai-lang-swift
Swift 6.0 enterprise development with async/await, SwiftUI, Combine, and Swift Concurrency. Advanced patterns for iOS, macOS, server-side Swift, and enterprise mobile applications with Context7 MCP integration.
What this skill does
# Swift - Enterprise
## Metadata
| Field | Value |
| ----- | ----- |
| **Skill Name** | moai-lang-swift |
| **Version** | 4.0.0 (2025-11-12) |
| **Allowed tools** | Read, Bash, Context7 MCP |
| **Auto-load** | On demand when keywords detected |
| **Tier** | Language Enterprise |
| **Context7 Integration** | ✅ Swift/SwiftUI/Vapor/Combine |
---
## What It Does
Swift 6.0 enterprise development featuring modern concurrency with async/await, SwiftUI for declarative UI, Combine for reactive programming, server-side Swift with Vapor, and enterprise-grade patterns for scalable, performant applications. Context7 MCP integration provides real-time access to official Swift and ecosystem documentation.
**Key capabilities**:
- ✅ Swift 6.0 with strict concurrency and actor isolation
- ✅ Advanced async/await patterns and structured concurrency
- ✅ SwiftUI 6.0 for declarative UI development
- ✅ Combine framework for reactive programming
- ✅ Server-side Swift with Vapor 4.x
- ✅ Enterprise architecture patterns (MVVM, TCA, Clean Architecture)
- ✅ Context7 MCP integration for real-time docs
- ✅ Performance optimization and memory management
- ✅ Testing strategies with XCTest and Swift Testing
- ✅ Swift Concurrency with actors and distributed actors
---
## When to Use
**Automatic triggers**:
- Swift 6.0 development discussions
- SwiftUI and iOS/macOS app development
- Async/await and concurrency patterns
- Combine reactive programming
- Server-side Swift and Vapor development
- Enterprise mobile application architecture
**Manual invocation**:
- Design iOS/macOS application architecture
- Implement async/await patterns
- Optimize performance and memory usage
- Review enterprise Swift code
- Implement reactive UI with Combine
- Troubleshoot concurrency issues
---
## Technology Stack (2025-11-12)
| Component | Version | Purpose | Status |
|-----------|---------|---------|--------|
| **Swift** | 6.0.1 | Core language | ✅ Current |
| **SwiftUI** | 6.0 | Declarative UI | ✅ Current |
| **Combine** | 6.0 | Reactive programming | ✅ Current |
| **Vapor** | 4.102.0 | Server-side framework | ✅ Current |
| **Xcode** | 16.2 | Development environment | ✅ Current |
| **Swift Concurrency** | 6.0 | Async/await & actors | ✅ Current |
| **Swift Testing** | 0.10.0 | Modern testing framework | ✅ Current |
---
## Quick Start: Hello Async/Await
```swift
import Foundation
// Swift 6.0 with async/await
actor GreeterService {
func greet(name: String) -> String {
"Hello, \(name)!"
}
}
// Usage
Task {
let service = GreeterService()
let greeting = await service.greet(name: "Swift")
print(greeting)
}
```
---
## Level 1: Quick Reference
### Core Concepts
1. **Async/Await** - Modern concurrency without callbacks
- Function marked with `async` - Suspends for I/O
- Caller uses `await` - Waits for result
- Native error handling with `throws`
- Replaces callbacks and completion handlers
2. **SwiftUI** - Declarative UI framework
- State-driven views update automatically
- `@State` for local state
- `@StateObject` for ViewModels
- Composable views with modifiers
3. **Combine** - Reactive programming
- Publishers emit values
- Operators transform pipelines
- Subscribers receive results
- Error handling with `.catch`
4. **Actors** - Thread-safe state isolation
- Protect mutable state automatically
- Replace locks and semaphores
- `@MainActor` for UI thread
- Distributed actors for RPC
5. **Vapor** - Server-side Swift
- Async route handlers
- Database integration (Fluent)
- Middleware for cross-cutting concerns
- Type-safe API responses
### Project Structure
```
MyApp/
├── Sources/
│ ├── App.swift # Entry point
│ ├── Models/ # Data types
│ ├── Services/ # Business logic
│ ├── ViewModels/ # UI state management
│ └── Views/ # SwiftUI components
├── Tests/
│ ├── UnitTests/
│ └── IntegrationTests/
└── Package.swift # Dependencies
```
---
## Level 2: Implementation Patterns
### Async/Await Pattern
```swift
import Foundation
// Structured async function
func fetchData() async throws -> String {
let url = URL(string: "https://api.example.com/data")!
let (data, _) = try await URLSession.shared.data(from: url)
return String(data: data, encoding: .utf8) ?? ""
}
// Concurrent operations with TaskGroup
func loadMultipleResources() async throws -> (String, String) {
try await withThrowingTaskGroup(of: (String, String).self) { group in
group.addTask { ("users", try await fetchUsers()) }
group.addTask { ("posts", try await fetchPosts()) }
var results: [String: String] = [:]
for try await (key, value) in group {
results[key] = value
}
return (results["users"] ?? "", results["posts"] ?? "")
}
}
```
### SwiftUI State Management
```swift
import SwiftUI
@MainActor
class ContentViewModel: ObservableObject {
@Published var items: [String] = []
@Published var isLoading = false
func loadItems() async {
isLoading = true
defer { isLoading = false }
do {
items = try await fetchItems()
} catch {
items = []
}
}
}
struct ContentView: View {
@StateObject private var viewModel = ContentViewModel()
var body: some View {
NavigationView {
VStack {
if viewModel.isLoading {
ProgressView()
} else {
List(viewModel.items, id: \.self) { item in
Text(item)
}
}
}
.navigationTitle("Items")
.task {
await viewModel.loadItems()
}
}
}
}
```
### Actor Isolation Pattern
```swift
// Thread-safe counter
actor CounterService {
private var count: Int = 0
func increment() { count += 1 }
func decrement() { count -= 1 }
func getCount() -> Int { count }
}
// Usage (automatically thread-safe)
Task {
let counter = CounterService()
await counter.increment()
let value = await counter.getCount()
}
```
### Vapor Server Route
```swift
import Vapor
func routes(_ app: Application) throws {
// GET /api/users
app.get("api", "users") { req async -> [String: String] in
return ["status": "success"]
}
// POST /api/users
app.post("api", "users") { req async -> HTTPStatus in
// Save user
return .created
}
}
```
---
## Level 3: Advanced Topics
### Concurrency Best Practices
1. **Prefer async/await** over Combine for sequential operations
2. **Use actors** for mutable shared state (not locks)
3. **Mark UI code @MainActor** to ensure main thread
4. **Handle cancellation** properly in long-running tasks
5. **Avoid blocking operations** (no sleep, no synchronous I/O)
### Performance Optimization
- **Memory**: Use value types (struct) by default
- **CPU**: Profile with Xcode Instruments
- **Rendering**: Keep SwiftUI view body pure
- **Networking**: Implement request caching
- **Database**: Use connection pooling in Vapor
### Security Patterns
- **Input validation**: Always validate user input
- **Error handling**: Don't expose internal errors to users
- **Encryption**: Use CryptoKit for sensitive data
- **Authentication**: Implement JWT or OAuth2
- **SQL injection prevention**: Use parameterized queries
### Testing Strategy
- **Unit tests**: Pure functions with XCTest
- **Integration tests**: Database and API tests
- **UI tests**: SwiftUI view behavior
- **Mocking**: Use protocols for dependency injection
---
## Context7 MCP Integration
**Get latest Swift documentation on-demand:**
```python
# Access Swift documentation via Context7
from context7 import resolve_library_id, get_library_docs
# Swift Language Documentation
swift_id = resolve_library_id("swift")
docsRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.